Commit cd63ed77 authored by Grigory Fedorov's avatar Grigory Fedorov

Merge branch 'feature/smack' into develop

parents 3dac8b3f b9e1f2f5
[submodule "app/otr4j"]
path = app/otr4j
url = https://github.com/otr4j/otr4j.git
[submodule "app/MemorizingTrustManager"]
path = app/MemorizingTrustManager
url = https://github.com/ge0rg/MemorizingTrustManager.git
Subproject commit 8b80fb176542fa96c1028c379be8de7e32c730df
......@@ -7,8 +7,8 @@ android {
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
versionCode 206
versionName '1.0.33'
versionCode 210
versionName '1.0.37'
}
compileOptions {
......@@ -50,6 +50,10 @@ repositories {
mavenCentral()
}
ext {
smackVersion = '4.1.3'
}
dependencies {
compile 'com.android.support:design:22.2.1'
compile 'com.android.support:appcompat-v7:22.2.1'
......@@ -61,5 +65,12 @@ dependencies {
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'com.google.zxing:android-integration:3.1.0'
compile 'com.jcraft:jzlib:1.0.7'
compile "org.igniterealtime.smack:smack-android-extensions:$smackVersion"
compile "org.igniterealtime.smack:smack-experimental:$smackVersion"
compile "org.igniterealtime.smack:smack-tcp:$smackVersion"
compile project('otr4j')
compile project('MemorizingTrustManager')
compile 'com.soundcloud.android:android-crop:1.0.0@aar'
}
......@@ -32,6 +32,7 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:name=".data.Application"
......@@ -244,6 +245,27 @@
android:name="android.support.PARENT_ACTIVITY"
android:value="com.xabber.android.ui.ChatViewer" />
</activity>
<activity
android:name=".ui.AccountViewer"
android:parentActivityName=".ui.ContactList" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.xabber.android.ui.ContactList" />
</activity>
<activity
android:name=".ui.AccountInfoEditor"
android:parentActivityName=".ui.AccountViewer" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.xabber.android.ui.AccountViewer" />
</activity>
<activity
android:name=".ui.FingerprintViewer"
android:label="@string/otr_verify_fingerprint"
......@@ -417,6 +439,13 @@
<action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
</intent-filter>
</receiver>
<activity
android:name="de.duenndns.ssl.MemorizingActivity"
/>
<activity android:name="com.soundcloud.android.crop.CropImageActivity" />
<receiver android:name=".receiver.GoAwayReceiver" />
<receiver android:name=".receiver.GoXaReceiver" />
<receiver android:name=".receiver.ComposingPausedReceiver" />
......
/* **************************************************************************
* $OpenLDAP: /com/novell/sasl/client/ParsedDirective.java,v 1.1 2003/08/21 10:06:26 kkanil Exp $
*
* Copyright (C) 2002 Novell, Inc. All Rights Reserved.
*
* THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND
* TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT
* TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS
* AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE"
* IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION
* OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP
* PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT
* THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY.
******************************************************************************/
package com.novell.sasl.client;
/**
* Implements the ParsedDirective class which will be used in the
* DigestMD5SaslClient mechanism.
*/
class ParsedDirective {
public static final int QUOTED_STRING_VALUE = 1;
public static final int TOKEN_VALUE = 2;
private int m_valueType;
private String m_name;
private String m_value;
ParsedDirective(
String name,
String value,
int type) {
m_name = name;
m_value = value;
m_valueType = type;
}
String getValue() {
return m_value;
}
String getName() {
return m_name;
}
int getValueType() {
return m_valueType;
}
}
/* **************************************************************************
* $OpenLDAP: /com/novell/sasl/client/ResponseAuth.java,v 1.3 2005/01/17 15:00:54 sunilk Exp $
*
* Copyright (C) 2002 Novell, Inc. All Rights Reserved.
*
* THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND
* TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT
* TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS
* AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE"
* IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION
* OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP
* PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT
* THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY.
******************************************************************************/
package com.novell.sasl.client;
import java.util.*;
import org.apache.harmony.javax.security.sasl.*;
/**
* Implements the ResponseAuth class used by the DigestMD5SaslClient mechanism
*/
class ResponseAuth {
private String m_responseValue;
ResponseAuth(
byte[] responseAuth)
throws SaslException {
m_responseValue = null;
DirectiveList dirList = new DirectiveList(responseAuth);
try {
dirList.parseDirectives();
checkSemantics(dirList);
} catch (SaslException e) {
}
}
/**
* Checks the semantics of the directives in the directive list as parsed
* from the digest challenge byte array.
*
* @param dirList the list of directives parsed from the digest challenge
* @throws SaslException If a semantic error occurs
*/
void checkSemantics(
DirectiveList dirList) throws SaslException {
Iterator directives = dirList.getIterator();
ParsedDirective directive;
String name;
while (directives.hasNext()) {
directive = (ParsedDirective) directives.next();
name = directive.getName();
if (name.equals("rspauth"))
m_responseValue = directive.getValue();
}
/* post semantic check */
if (m_responseValue == null)
throw new SaslException("Missing response-auth directive.");
}
/**
* returns the ResponseValue
*
* @return the ResponseValue as a String.
*/
public String getResponseValue() {
return m_responseValue;
}
}
/* **************************************************************************
* $OpenLDAP: /com/novell/sasl/client/TokenParser.java,v 1.3 2005/01/17 15:00:54 sunilk Exp $
*
* Copyright (C) 2002 Novell, Inc. All Rights Reserved.
*
* THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND
* TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT
* TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS
* AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE"
* IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION
* OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP
* PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT
* THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY.
******************************************************************************/
package com.novell.sasl.client;
import org.apache.harmony.javax.security.sasl.*;
/**
* The TokenParser class will parse individual tokens from a list of tokens that
* are a directive value for a DigestMD5 authentication.The tokens are separated
* commas.
*/
class TokenParser extends Object {
private static final int STATE_LOOKING_FOR_FIRST_TOKEN = 1;
private static final int STATE_LOOKING_FOR_TOKEN = 2;
private static final int STATE_SCANNING_TOKEN = 3;
private static final int STATE_LOOKING_FOR_COMMA = 4;
private static final int STATE_PARSING_ERROR = 5;
private static final int STATE_DONE = 6;
private int m_curPos;
private int m_scanStart;
private int m_state;
private String m_tokens;
TokenParser(
String tokens) {
m_tokens = tokens;
m_curPos = 0;
m_scanStart = 0;
m_state = STATE_LOOKING_FOR_FIRST_TOKEN;
}
/**
* This function parses the next token from the tokens string and returns
* it as a string. If there are no more tokens a null reference is returned.
*
* @return the parsed token or a null reference if there are no more
* tokens
* @throws SASLException if an error occurs while parsing
*/
String parseToken() throws SaslException {
char currChar;
String token = null;
if (m_state == STATE_DONE)
return null;
while (m_curPos < m_tokens.length() && (token == null)) {
currChar = m_tokens.charAt(m_curPos);
switch (m_state) {
case STATE_LOOKING_FOR_FIRST_TOKEN:
case STATE_LOOKING_FOR_TOKEN:
if (isWhiteSpace(currChar)) {
break;
} else if (isValidTokenChar(currChar)) {
m_scanStart = m_curPos;
m_state = STATE_SCANNING_TOKEN;
} else {
m_state = STATE_PARSING_ERROR;
throw new SaslException("Invalid token character at position " + m_curPos);
}
break;
case STATE_SCANNING_TOKEN:
if (isValidTokenChar(currChar)) {
break;
} else if (isWhiteSpace(currChar)) {
token = m_tokens.substring(m_scanStart, m_curPos);
m_state = STATE_LOOKING_FOR_COMMA;
} else if (',' == currChar) {
token = m_tokens.substring(m_scanStart, m_curPos);
m_state = STATE_LOOKING_FOR_TOKEN;
} else {
m_state = STATE_PARSING_ERROR;
throw new SaslException("Invalid token character at position " + m_curPos);
}
break;
case STATE_LOOKING_FOR_COMMA:
if (isWhiteSpace(currChar))
break;
else if (currChar == ',')
m_state = STATE_LOOKING_FOR_TOKEN;
else {
m_state = STATE_PARSING_ERROR;
throw new SaslException("Expected a comma, found '" +
currChar + "' at postion " +
m_curPos);
}
break;
}
m_curPos++;
} /* end while loop */
if (token == null) { /* check the ending state */
switch (m_state) {
case STATE_SCANNING_TOKEN:
token = m_tokens.substring(m_scanStart);
m_state = STATE_DONE;
break;
case STATE_LOOKING_FOR_FIRST_TOKEN:
case STATE_LOOKING_FOR_COMMA:
break;
case STATE_LOOKING_FOR_TOKEN:
throw new SaslException("Trialing comma");
}
}
return token;
}
/**
* This function returns TRUE if the character is a valid token character.
* <p/>
* token = 1*<any CHAR except CTLs or separators>
* <p/>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
* <p/>
* CTL = <any US-ASCII control character
* (octets 0 - 31) and DEL (127)>
* <p/>
* CHAR = <any US-ASCII character (octets 0 - 127)>
*
* @param c character to be validated
* @return True if character is valid Token character else it returns
* false
*/
boolean isValidTokenChar(
char c) {
if (((c >= '\u0000') && (c <= '\u0020')) ||
((c >= '\u003a') && (c <= '\u0040')) ||
((c >= '\u005b') && (c <= '\u005d')) ||
('\u002c' == c) ||
('\u0025' == c) ||
('\u0028' == c) ||
('\u0029' == c) ||
('\u007b' == c) ||
('\u007d' == c) ||
('\u007f' == c))
return false;
return true;
}
/**
* This function returns TRUE if the character is linear white space (LWS).
* LWS = [CRLF] 1*( SP | HT )
*
* @param c character to be validated
* @return True if character is liner whitespace else it returns false
*/
boolean isWhiteSpace(
char c) {
if (('\t' == c) || // HORIZONTAL TABULATION.
('\n' == c) || // LINE FEED.
('\r' == c) || // CARRIAGE RETURN.
('\u0020' == c))
return true;
return false;
}
}
......@@ -22,6 +22,9 @@ import android.os.Handler;
import com.xabber.android.R;
import com.xabber.android.service.XabberService;
import org.jivesoftware.smack.provider.ProviderFileLoader;
import org.jivesoftware.smack.provider.ProviderManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
......@@ -133,6 +136,8 @@ public class Application extends android.app.Application {
}
private void onLoad() {
ProviderManager.addLoader(new ProviderFileLoader(getResources().openRawResource(R.raw.smack)));
for (OnLoadListener listener : getManagers(OnLoadListener.class)) {
LogManager.i(listener, "onLoad");
listener.onLoad();
......
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
*
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.xabber.android.data;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.debugger.ConsoleDebugger;
import org.jivesoftware.smack.util.ReaderListener;
import org.jivesoftware.smack.util.WriterListener;
import android.os.Environment;
/**
* Writer for connection log to the file.
*
* @author alexander.ivanov
*/
public class FileLogDebugger extends ConsoleDebugger {
private FileWriter writer;
private boolean readerClosed;
private boolean writerClosed;
private final static SimpleDateFormat FILE_NAME_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
public FileLogDebugger(Connection connection, Writer writer, Reader reader) {
super(connection, writer, reader);
File dir = new File(Environment.getExternalStorageDirectory(),
"xabber-log");
dir.mkdirs();
File file = new File(dir, FILE_NAME_FORMAT.format(new Date()) + " - "
+ connection.hashCode() + ".xml");
try {
this.writer = new FileWriter(file);
this.writer.write("<xml>");
this.writer.write("\n");
this.writer.flush();
} catch (IOException e) {
LogManager.forceException(this, e);
}
}
@Override
protected ReaderListener createReaderListener() {
final ReaderListener inherited = super.createReaderListener();
return new ReaderListener() {
@Override
public void read(String str) {
inherited.read(str);
synchronized (this) {
if (writerClosed && readerClosed)
return;
try {
writer.write("\n");
writer.write(dateFormatter.format(new Date()));
writer.write(" RCV ");
writer.write(str);
writer.flush();
} catch (IOException e) {
LogManager.forceException(this, e);
}
}
}
@Override
public void close() {
inherited.close();
System.out.println(dateFormatter.format(new Date())
+ " RCV CLOSED (" + connection.hashCode() + ")");
synchronized (this) {
if (readerClosed)
return;
try {
writer.write("\n");
writer.write(dateFormatter.format(new Date()));
writer.write(" RCV - CLOSED ");
writer.flush();
} catch (IOException e) {
LogManager.exception(this, e);
}
readerClosed = true;
onClose();
}
}
};
}
@Override
protected WriterListener createWriterListener() {
final WriterListener inherited = super.createWriterListener();
return new WriterListener() {
@Override
public void write(String str) {
inherited.write(str);
synchronized (this) {
if (writerClosed && readerClosed)
return;
try {
writer.write("\n");
writer.write(dateFormatter.format(new Date()));
writer.write(" SNT ");
writer.write(str);
writer.flush();
} catch (IOException e) {
LogManager.forceException(this, e);
}
}
}
@Override
public void close() {
inherited.close();
System.out.println(dateFormatter.format(new Date())
+ " SENT CLOSED (" + connection.hashCode() + ")");
synchronized (this) {
if (writerClosed)
return;
try {
writer.write("\n");
writer.write(dateFormatter.format(new Date()));
writer.write(" SNT - CLOSED");
writer.flush();
} catch (IOException e) {
LogManager.exception(this, e);
}
writerClosed = true;
onClose();
}
}
};
}
private void onClose() {
if (writerClosed && readerClosed) {
try {
writer.write("\n");
writer.write("</xml>");
writer.close();
} catch (IOException e) {
LogManager.exception(this, e);
}
}
}
}
......@@ -17,7 +17,7 @@ package com.xabber.android.data;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.SmackConfiguration;
import org.xbill.DNS.Options;
import android.content.pm.ApplicationInfo;
......@@ -59,7 +59,7 @@ public class LogManager implements OnLoadListener {
"org.jivesoftware.smack.debugger.ConsoleDebugger");
// "com.xabber.android.data.FileLogDebugger");
System.setProperty("smack.debugEnabled", "true");
Connection.DEBUG_ENABLED = true;
SmackConfiguration.DEBUG = true;
Options.set("verbose");
Options.set("verbosemsg");
Options.set("verbosecompression");
......
......@@ -36,6 +36,7 @@ import com.xabber.android.data.roster.RosterManager;
import com.xabber.xmpp.address.Jid;
import org.jivesoftware.smack.util.StringUtils;
import org.jxmpp.util.XmppStringUtils;
import java.security.KeyPair;
import java.util.ArrayList;
......@@ -54,7 +55,7 @@ import java.util.Map;
* Each account has unique full jid (userName@serverName/resource). This jid is
* persistent and independent from real jid assigned by server. Real full jid
* (assigned by server) of account can be taken by
* {@link AccountItem#getRealAccount()}.
* {@link AccountItem#getRealJid()}.
*
* @author alexander.ivanov
*/
......@@ -353,9 +354,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
}
}
String serverName = StringUtils.parseServer(user);
String userName = StringUtils.parseName(user);
String resource = StringUtils.parseResource(user);
String serverName = XmppStringUtils.parseDomain(user);
String userName = XmppStringUtils.parseLocalpart(user);
String resource = XmppStringUtils.parseResource(user);
String host = accountType.getHost();
int port = accountType.getPort();
boolean tlsRequired = accountType.isTLSRequired();
......@@ -503,7 +504,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
result.setColorIndex(colorIndex);
boolean reconnect = false;
if (accountItem.getConnectionSettings().isCustom() != custom
if (accountItem.getConnectionSettings().isCustomHostAndPort() != custom
|| !accountItem.getConnectionSettings().getHost().equals(host)
|| accountItem.getConnectionSettings().getPort() != port
|| !accountItem.getConnectionSettings().getPassword().equals(password)
......@@ -595,7 +596,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
updateAccount(
account,
connectionSettings.isCustom(),
connectionSettings.isCustomHostAndPort(),
connectionSettings.getHost(),
connectionSettings.getPort(),
connectionSettings.getServerName(),
......@@ -624,7 +625,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
updateAccount(
account,
connectionSettings.isCustom(),
connectionSettings.isCustomHostAndPort(),
connectionSettings.getHost(),
connectionSettings.getPort(),
connectionSettings.getServerName(),
......@@ -653,7 +654,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
AccountManager.getInstance().updateAccount(
account,
connectionSettings.isCustom(),
connectionSettings.isCustomHostAndPort(),
connectionSettings.getHost(),
connectionSettings.getPort(),
connectionSettings.getServerName(),
......@@ -948,10 +949,6 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
/**
* Sets status for account.
*
* @param account
* @param statusMode
* @param statusText
*/
private void setStatus(AccountItem accountItem, StatusMode statusMode, String statusText) {
boolean changed = accountItem.isEnabled()
......@@ -1012,9 +1009,6 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
/**
* Remove status from presets.
*
* @param statusMode
* @param statusText
*/
public void removeSavedStatus(final SavedStatus savedStatus) {
if (!savedStatuses.remove(savedStatus)) {
......
......@@ -409,7 +409,7 @@ class AccountTable extends AbstractTable {
ContentValues values = new ContentValues();
values.put(Fields.PROTOCOL, connectionSettings.getProtocol().name());
values.put(Fields.CUSTOM, connectionSettings.isCustom() ? 1 : 0);
values.put(Fields.CUSTOM, connectionSettings.isCustomHostAndPort() ? 1 : 0);
values.put(Fields.HOST, connectionSettings.getHost());
values.put(Fields.PORT, connectionSettings.getPort());
values.put(Fields.SERVER_NAME, connectionSettings.getServerName());
......
......@@ -24,7 +24,6 @@ import com.xabber.android.data.OnLoadListener;
import com.xabber.android.data.notification.BaseNotificationProvider;
import com.xabber.android.data.notification.NotificationManager;
import org.jivesoftware.smack.CertificateListener;
import org.jivesoftware.smack.util.StringUtils;
import java.io.File;
......@@ -416,43 +415,4 @@ public class CertificateManager implements OnLoadListener, OnClearListener {
});
}
public CertificateListener createCertificateListener(
ConnectionItem connectionItem) {
final String server = connectionItem.getConnectionSettings()
.getServerName();
return new CertificateListener() {
@Override
public boolean onValid(X509Certificate[] chain) {
return true;
}
@Override
public boolean onSelfSigned(X509Certificate certificate,
CertificateException exception) {
LogManager.exception(CertificateManager.this, exception);
return isTrustedCertificate(server, certificate,
CertificateInvalidReason.selfSigned);
}
@Override
public boolean onInvalidTarget(X509Certificate certificate,
CertificateException exception) {
LogManager.exception(CertificateManager.this, exception);
return isTrustedCertificate(server, certificate,
CertificateInvalidReason.invalidTarget);
}
@Override
public boolean onInvalidChain(X509Certificate[] chain,
CertificateException exception) {
LogManager.exception(CertificateManager.this, exception);
return isTrustedCertificate(server, chain[0],
CertificateInvalidReason.invalidChane);
}
};
}
}
......@@ -19,6 +19,7 @@ import com.xabber.android.data.Application;
import com.xabber.android.data.LogManager;
import com.xabber.android.data.account.AccountProtocol;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.XMPPConnection;
/**
......@@ -41,7 +42,7 @@ public abstract class ConnectionItem {
/**
* Connection was requested by user.
*/
private boolean connectionRequest;
private boolean isConnectionRequestedByUser;
/**
* Current state.
......@@ -68,7 +69,7 @@ public abstract class ConnectionItem {
serverName, resource, custom, host, port, password,
saslEnabled, tlsMode, compression, proxyType, proxyHost,
proxyPort, proxyUser, proxyPassword);
connectionRequest = false;
isConnectionRequestedByUser = false;
disconnectionRequested = false;
connectionThread = null;
state = ConnectionState.offline;
......@@ -115,14 +116,17 @@ public abstract class ConnectionItem {
*/
public String getRealJid() {
ConnectionThread connectionThread = getConnectionThread();
if (connectionThread == null)
if (connectionThread == null) {
return null;
}
XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
if (xmppConnection == null)
if (xmppConnection == null) {
return null;
}
String user = xmppConnection.getUser();
if (user == null)
if (user == null) {
return null;
}
return user;
}
......@@ -144,13 +148,12 @@ public abstract class ConnectionItem {
boolean available = isConnectionAvailable(userRequest);
if (NetworkManager.getInstance().getState() != NetworkState.available
|| !available || disconnectionRequested) {
ConnectionState target = available ? ConnectionState.waiting
: ConnectionState.offline;
if (state == ConnectionState.connected
|| state == ConnectionState.authentication
ConnectionState target = available ? ConnectionState.waiting : ConnectionState.offline;
if (state == ConnectionState.connected || state == ConnectionState.authentication
|| state == ConnectionState.connecting) {
if (userRequest)
connectionRequest = false;
if (userRequest) {
isConnectionRequestedByUser = false;
}
if (connectionThread != null) {
disconnect(connectionThread);
// Force remove managed connection thread.
......@@ -163,18 +166,28 @@ public abstract class ConnectionItem {
state = target;
return true;
} else {
if (state == ConnectionState.offline
|| state == ConnectionState.waiting) {
if (userRequest)
connectionRequest = true;
if (state == ConnectionState.offline || state == ConnectionState.waiting) {
if (userRequest) {
isConnectionRequestedByUser = true;
}
state = ConnectionState.connecting;
connectionThread = new ConnectionThread(this);
if (connectionSettings.isCustom())
connectionThread.start(connectionSettings.getHost(),
connectionSettings.getPort(), false, registerNewAccount);
else
connectionThread.start(connectionSettings.getServerName(),
5222, true, registerNewAccount);
boolean useSRVLookup;
String fullyQualifiedDomainName;
int port;
if (connectionSettings.isCustomHostAndPort()) {
fullyQualifiedDomainName = connectionSettings.getHost();
port = connectionSettings.getPort();
useSRVLookup = false;
} else {
fullyQualifiedDomainName = connectionSettings.getServerName();
port = 5222;
useSRVLookup = true;
}
connectionThread.start(fullyQualifiedDomainName, port, useSRVLookup, registerNewAccount);
return true;
} else {
return false;
......@@ -186,13 +199,14 @@ public abstract class ConnectionItem {
* Disconnect and connect using new connection.
*/
public void forceReconnect() {
if (!getState().isConnectable())
if (!getState().isConnectable()) {
return;
}
disconnectionRequested = true;
boolean request = connectionRequest;
connectionRequest = false;
boolean request = isConnectionRequestedByUser;
isConnectionRequestedByUser = false;
updateConnection(false);
connectionRequest = request;
isConnectionRequestedByUser = request;
disconnectionRequested = false;
updateConnection(false);
}
......@@ -204,8 +218,7 @@ public abstract class ConnectionItem {
Thread thread = new Thread("Disconnection thread for " + this) {
@Override
public void run() {
XMPPConnection xmppConnection = connectionThread
.getXMPPConnection();
AbstractXMPPConnection xmppConnection = connectionThread.getXMPPConnection();
if (xmppConnection != null)
try {
xmppConnection.disconnect();
......@@ -253,10 +266,11 @@ public abstract class ConnectionItem {
* Connection has been established.
*/
protected void onConnected(ConnectionThread connectionThread) {
if (isRegisterAccount())
if (isRegisterAccount()) {
state = ConnectionState.registration;
else if (isManaged(connectionThread))
} else if (isManaged(connectionThread)) {
state = ConnectionState.authentication;
}
}
/**
......@@ -264,8 +278,9 @@ public abstract class ConnectionItem {
*/
protected void onAccountRegistered(ConnectionThread connectionThread) {
registerNewAccount = false;
if (isManaged(connectionThread))
if (isManaged(connectionThread)) {
state = ConnectionState.authentication;
}
}
/**
......@@ -278,8 +293,9 @@ public abstract class ConnectionItem {
* Authorization passed.
*/
protected void onAuthorized(ConnectionThread connectionThread) {
if (isManaged(connectionThread))
if (isManaged(connectionThread)) {
state = ConnectionState.connected;
}
}
/**
......@@ -291,16 +307,17 @@ public abstract class ConnectionItem {
private boolean onDisconnect(ConnectionThread connectionThread) {
XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
boolean acceptable = isManaged(connectionThread);
if (xmppConnection == null)
if (xmppConnection == null) {
LogManager.i(this, "onClose " + acceptable);
else
LogManager
.i(this, "onClose " + xmppConnection.hashCode() + " - "
+ xmppConnection.connectionCounterValue + ", "
+ acceptable);
} else {
LogManager.i(this, "onClose " + xmppConnection.hashCode() + " - "
+ xmppConnection.getConnectionCounter() + ", " + acceptable);
}
ConnectionManager.getInstance().onDisconnect(connectionThread);
if (acceptable)
if (acceptable) {
connectionThread.shutdown();
}
return acceptable;
}
......@@ -311,9 +328,10 @@ public abstract class ConnectionItem {
if (onDisconnect(connectionThread)) {
state = ConnectionState.waiting;
this.connectionThread = null;
if (connectionRequest)
if (isConnectionRequestedByUser) {
Application.getInstance().onError(R.string.CONNECTION_FAILED);
connectionRequest = false;
}
isConnectionRequestedByUser = false;
}
}
......
......@@ -133,7 +133,7 @@ public class ConnectionSettings {
/**
* @return Whether custom host and port must be used.
*/
public boolean isCustom() {
public boolean isCustomHostAndPort() {
return custom;
}
......
......@@ -14,10 +14,10 @@
*/
package com.xabber.android.data.connection;
import org.jivesoftware.smack.packet.Packet;
import com.xabber.android.data.BaseManagerInterface;
import org.jivesoftware.smack.packet.Stanza;
/**
* Listener for incoming packet.
*
......@@ -33,6 +33,6 @@ public interface OnPacketListener extends BaseManagerInterface {
* @param packet
* @return
*/
void onPacket(ConnectionItem connection, String bareAddress, Packet packet);
void onPacket(ConnectionItem connection, String bareAddress, Stanza packet);
}
......@@ -41,11 +41,11 @@ public enum TLSMode {
SecurityMode getSecurityMode() {
if (this == enabled)
return SecurityMode.enabled;
return SecurityMode.ifpossible;
else if (this == required)
return SecurityMode.required;
else if (this == legacy)
return SecurityMode.legacy;
return SecurityMode.disabled;
else
throw new IllegalStateException();
}
......
......@@ -60,7 +60,7 @@ import com.xabber.xmpp.rsm.Set;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Stanza;
import java.util.Collection;
import java.util.Date;
......@@ -294,8 +294,7 @@ public class MessageArchiveManager implements OnPacketListener,
}
@Override
public void onPacket(ConnectionItem connection, final String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, final String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem))
return;
String account = ((AccountItem) connection).getAccount();
......@@ -306,19 +305,19 @@ public class MessageArchiveManager implements OnPacketListener,
if (!(packet instanceof IQ))
return;
IQ iq = (IQ) packet;
if (iq.getType() == Type.SET && packet instanceof Pref
if (iq.getType() == Type.set && packet instanceof Pref
&& ((Pref) packet).isValid())
onPreferenceReceived(account, (Pref) packet);
else if (iq.getType() == Type.SET && packet instanceof ItemRemove
else if (iq.getType() == Type.set && packet instanceof ItemRemove
&& ((ItemRemove) packet).isValid())
onItemRemoveReceived(account, (ItemRemove) packet);
else if (iq.getType() == Type.SET && packet instanceof SessionRemove
else if (iq.getType() == Type.set && packet instanceof SessionRemove
&& ((SessionRemove) packet).isValid())
onSessionRemoveReceived(account, (SessionRemove) packet);
else if (iq.getType() == Type.RESULT && packet instanceof List
else if (iq.getType() == Type.result && packet instanceof List
&& ((List) packet).isValid())
onListReceived(account, (List) packet);
else if (iq.getType() == Type.RESULT && packet instanceof Chat
else if (iq.getType() == Type.result && packet instanceof Chat
&& ((Chat) packet).isValid())
onChatReceived(account, (Chat) packet);
}
......@@ -336,9 +335,9 @@ public class MessageArchiveManager implements OnPacketListener,
} else if (AccountManager.getInstance().getArchiveMode(account) == ArchiveMode.server) {
Auto auto = new Auto();
auto.setSave(true);
auto.setType(Type.SET);
auto.setType(Type.set);
try {
ConnectionManager.getInstance().sendPacket(account, auto);
ConnectionManager.getInstance().sendStanza(account, auto);
} catch (NetworkException e) {
}
// TODO: track results.
......@@ -393,9 +392,9 @@ public class MessageArchiveManager implements OnPacketListener,
defaultItem.setSave(SaveMode.body);
Pref pref = new Pref();
pref.setDefault(defaultItem);
pref.setType(Type.SET);
pref.setType(Type.set);
try {
ConnectionManager.getInstance().sendPacket(account, pref);
ConnectionManager.getInstance().sendStanza(account, pref);
} catch (NetworkException e) {
}
}
......@@ -543,7 +542,7 @@ public class MessageArchiveManager implements OnPacketListener,
private void requestPreferences(String account) {
Pref pref = new Pref();
pref.setType(Type.GET);
pref.setType(Type.get);
try {
ConnectionManager.getInstance().sendRequest(account, pref,
new OnResponseListener() {
......@@ -622,7 +621,7 @@ public class MessageArchiveManager implements OnPacketListener,
private void requestModified(String account, String before) {
Modified packet = new Modified();
packet.setType(Type.GET);
packet.setType(Type.get);
Set rsm = new Set();
rsm.setMax(RSM_MAX);
rsm.setBefore(before);
......@@ -695,7 +694,7 @@ public class MessageArchiveManager implements OnPacketListener,
private String requestList(String account, String bareAddress, String before) {
List packet = new List();
packet.setType(Type.GET);
packet.setType(Type.get);
Set rsm = new Set();
rsm.setMax(RSM_MAX);
rsm.setBefore(before);
......@@ -704,7 +703,7 @@ public class MessageArchiveManager implements OnPacketListener,
packet.setEnd(connected.get(account));
String packetId = packet.getPacketID();
try {
ConnectionManager.getInstance().sendPacket(account, packet);
ConnectionManager.getInstance().sendStanza(account, packet);
} catch (NetworkException e) {
}
return packetId;
......@@ -713,7 +712,7 @@ public class MessageArchiveManager implements OnPacketListener,
private void requestChat(String account, CollectionHeader header,
String after, boolean modification) {
Retrieve packet = new Retrieve();
packet.setType(Type.GET);
packet.setType(Type.get);
Set rsm = new Set();
rsm.setMax(RSM_MAX);
rsm.setAfter(after);
......@@ -723,7 +722,7 @@ public class MessageArchiveManager implements OnPacketListener,
modificationRequests.put(account, packet.getPacketID(), modification);
try {
if (!modification) {
ConnectionManager.getInstance().sendPacket(account, packet);
ConnectionManager.getInstance().sendStanza(account, packet);
return;
}
ConnectionManager.getInstance().sendRequest(account, packet,
......@@ -766,8 +765,8 @@ public class MessageArchiveManager implements OnPacketListener,
extension.setSave(saveMode);
Pref packet = new Pref();
packet.addItem(extension);
packet.setType(Type.SET);
ConnectionManager.getInstance().sendPacket(account, packet);
packet.setType(Type.set);
ConnectionManager.getInstance().sendStanza(account, packet);
}
private void sendItemRemove(String account, String user)
......@@ -776,8 +775,8 @@ public class MessageArchiveManager implements OnPacketListener,
extension.setJid(user);
ItemRemove packet = new ItemRemove();
packet.addItem(extension);
packet.setType(Type.SET);
ConnectionManager.getInstance().sendPacket(account, packet);
packet.setType(Type.set);
ConnectionManager.getInstance().sendStanza(account, packet);
}
public void setOtrMode(String account, String user, OtrMode otrMode)
......@@ -862,8 +861,8 @@ public class MessageArchiveManager implements OnPacketListener,
extension.setSave(saveMode);
Pref packet = new Pref();
packet.addSession(extension);
packet.setType(Type.SET);
ConnectionManager.getInstance().sendPacket(account, packet);
packet.setType(Type.set);
ConnectionManager.getInstance().sendStanza(account, packet);
sessionSaves.put(account, session, saveMode);
}
......@@ -873,8 +872,8 @@ public class MessageArchiveManager implements OnPacketListener,
extension.setThread(session);
SessionRemove packet = new SessionRemove();
packet.addSession(extension);
packet.setType(Type.SET);
ConnectionManager.getInstance().sendPacket(account, packet);
packet.setType(Type.set);
ConnectionManager.getInstance().sendStanza(account, packet);
sessionSaves.remove(account, session);
}
......
......@@ -42,15 +42,13 @@ import com.xabber.android.data.roster.ResourceItem;
import com.xabber.xmpp.address.Jid;
import com.xabber.xmpp.attention.Attention;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import java.util.Iterator;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
/**
* XEP-0224: Attention.
......@@ -68,18 +66,15 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
Application.getInstance().addManager(instance);
enabledLock = new Object();
Connection
.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final Connection connection) {
synchronized (enabledLock) {
if (SettingsManager.chatsAttention())
ServiceDiscoveryManager.getInstanceFor(
connection).addFeature(
Attention.NAMESPACE);
}
}
});
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final XMPPConnection connection) {
synchronized (enabledLock) {
if (SettingsManager.chatsAttention())
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(Attention.NAMESPACE);
}
}
});
}
private final EntityNotificationProvider<AttentionRequest> attentionRequestProvider = new EntityNotificationProvider<AttentionRequest>(
......@@ -121,10 +116,11 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
if (manager == null)
continue;
boolean contains = false;
for (Iterator<String> iterator = manager.getFeatures(); iterator
.hasNext(); )
if (Attention.NAMESPACE.equals(iterator.next()))
for (String feature : manager.getFeatures()) {
if (Attention.NAMESPACE.equals(feature)) {
contains = true;
}
}
if (SettingsManager.chatsAttention() == contains)
continue;
if (SettingsManager.chatsAttention())
......@@ -152,8 +148,7 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
}
@Override
public void onPacket(ConnectionItem connection, String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem))
return;
if (!(packet instanceof Message))
......@@ -163,7 +158,7 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
final String account = ((AccountItem) connection).getAccount();
if (bareAddress == null)
return;
for (PacketExtension packetExtension : packet.getExtensions())
for (ExtensionElement packetExtension : packet.getExtensions()) {
if (packetExtension instanceof Attention) {
MessageManager.getInstance().openChat(account, bareAddress);
MessageManager.getInstance()
......@@ -172,6 +167,7 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
attentionRequestProvider.add(new AttentionRequest(account,
bareAddress), true);
}
}
}
public void sendAttention(String account, String user)
......@@ -198,7 +194,7 @@ public class AttentionManager implements OnPacketListener, OnLoadListener {
message.setTo(to);
message.setType(Message.Type.headline);
message.addExtension(new Attention());
ConnectionManager.getInstance().sendPacket(account, message);
ConnectionManager.getInstance().sendStanza(account, message);
chat.newAction(null, null, ChatAction.attention_called);
}
......
......@@ -22,6 +22,7 @@ import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.annotation.NonNull;
import com.xabber.android.R;
import com.xabber.android.data.Application;
......@@ -37,9 +38,9 @@ import com.xabber.android.data.extension.vcard.VCardManager;
import com.xabber.xmpp.address.Jid;
import com.xabber.xmpp.avatar.VCardUpdate;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza;
import java.util.HashMap;
import java.util.HashSet;
......@@ -286,13 +287,18 @@ public class AvatarManager implements OnLoadListener, OnLowMemoryListener, OnPac
if (value != null) {
return new BitmapDrawable(application.getResources(), value);
} else {
Drawable[] layers = new Drawable[2];
layers[0] = new ColorDrawable(accountColors[AccountManager.getInstance().getColorLevel(account)]);
layers[1] = application.getResources().getDrawable(R.drawable.ic_avatar_1);
return new LayerDrawable(layers);
return getDefaultAccountAvatar(account);
}
}
@NonNull
public Drawable getDefaultAccountAvatar(String account) {
Drawable[] layers = new Drawable[2];
layers[0] = new ColorDrawable(accountColors[AccountManager.getInstance().getColorLevel(account)]);
layers[1] = application.getResources().getDrawable(R.drawable.ic_avatar_1);
return new LayerDrawable(layers);
}
/**
* Gets avatar for regular user.
*
......@@ -405,8 +411,7 @@ public class AvatarManager implements OnLoadListener, OnLowMemoryListener, OnPac
}
@Override
public void onPacket(ConnectionItem connection, String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, String bareAddress, Stanza packet) {
if (!(packet instanceof Presence) || bareAddress == null) {
return;
}
......@@ -418,7 +423,7 @@ public class AvatarManager implements OnLoadListener, OnLowMemoryListener, OnPac
if (presence.getType() == Presence.Type.error) {
return;
}
for (PacketExtension packetExtension : presence.getExtensions()) {
for (ExtensionElement packetExtension : presence.getExtensions()) {
if (packetExtension instanceof VCardUpdate) {
VCardUpdate vCardUpdate = (VCardUpdate) packetExtension;
if (vCardUpdate.isValid() && vCardUpdate.isPhotoReady()) {
......@@ -477,7 +482,7 @@ public class AvatarManager implements OnLoadListener, OnLowMemoryListener, OnPac
String hash, byte[] value, Bitmap bitmap) {
if (value == null) {
if (SettingsManager.connectionLoadVCard()) {
VCardManager.getInstance().request(account, bareAddress, hash);
VCardManager.getInstance().request(account, bareAddress);
}
} else {
bitmaps.put(hash, bitmap == null ? EMPTY_BITMAP : bitmap);
......
......@@ -17,10 +17,11 @@ package com.xabber.android.data.extension.capability;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.jivesoftware.smack.util.Base64;
import com.xabber.android.data.entity.BaseEntity;
import org.jivesoftware.smack.util.stringencoder.Base64;
class Capability extends BaseEntity {
private static final String SHA1_METHOD = "sha-1";
......@@ -80,7 +81,7 @@ class Capability extends BaseEntity {
try {
MessageDigest md = MessageDigest.getInstance(hash.toUpperCase());
byte[] digest = md.digest(value.getBytes());
return Base64.encodeBytes(digest);
return Base64.encodeToString(digest);
} catch (NoSuchAlgorithmException nsae) {
return null;
}
......
......@@ -14,17 +14,6 @@
*/
package com.xabber.android.data.extension.capability;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverInfo.Feature;
import com.xabber.android.data.Application;
import com.xabber.android.data.NetworkException;
import com.xabber.android.data.account.AccountItem;
......@@ -35,6 +24,15 @@ import com.xabber.android.data.connection.OnAuthorizedListener;
import com.xabber.android.data.connection.OnResponseListener;
import com.xabber.xmpp.address.Jid;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class ServerInfoManager implements OnAuthorizedListener,
OnResponseListener {
......@@ -66,7 +64,7 @@ public class ServerInfoManager implements OnAuthorizedListener,
if (protocols.get(account) == null) {
DiscoverInfo packet = new DiscoverInfo();
packet.setTo(Jid.getServer(account));
packet.setType(Type.GET);
packet.setType(Type.get);
try {
ConnectionManager.getInstance().sendRequest(account,
packet, this);
......@@ -92,9 +90,9 @@ public class ServerInfoManager implements OnAuthorizedListener,
}
ArrayList<String> features = new ArrayList<String>();
DiscoverInfo discoverInfo = (DiscoverInfo) iq;
Iterator<Feature> iterator = discoverInfo.getFeatures();
while (iterator.hasNext())
features.add(iterator.next().getVar());
for (DiscoverInfo.Feature feature : discoverInfo.getFeatures()) {
features.add(feature.getVar());
}
protocols.put(account, features);
onAvailable(AccountManager.getInstance().getAccount(account));
}
......@@ -116,9 +114,7 @@ public class ServerInfoManager implements OnAuthorizedListener,
public boolean isProtocolSupported(String account, String feature) {
Collection<String> collection = protocols.get(account);
if (collection == null)
return false;
return collection.contains(feature);
return collection != null && collection.contains(feature);
}
}
......@@ -38,16 +38,17 @@ import com.xabber.android.data.roster.RosterManager;
import com.xabber.android.receiver.ComposingPausedReceiver;
import com.xabber.xmpp.address.Jid;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smackx.ChatState;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.chatstates.ChatState;
import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import java.util.Calendar;
import java.util.Map;
......@@ -70,14 +71,11 @@ public class ChatStateManager implements OnDisconnectListener,
instance = new ChatStateManager();
Application.getInstance().addManager(instance);
Connection
.addConnectionCreationListener(new ConnectionCreationListener() {
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final Connection connection) {
ServiceDiscoveryManager
.getInstanceFor(connection)
.addFeature(
"http://jabber.org/protocol/chatstates");
public void connectionCreated(final XMPPConnection connection) {
ServiceDiscoveryManager.getInstanceFor(connection)
.addFeature("http://jabber.org/protocol/chatstates");
}
});
}
......@@ -217,7 +215,7 @@ public class ChatStateManager implements OnDisconnectListener,
message.setTo(chat.getTo());
message.addExtension(new ChatStateExtension(chatState));
try {
ConnectionManager.getInstance().sendPacket(account, message);
ConnectionManager.getInstance().sendStanza(account, message);
} catch (NetworkException e) {
// Just ignore it.
}
......@@ -238,7 +236,7 @@ public class ChatStateManager implements OnDisconnectListener,
/**
* Must be call each time user change text message.
*
* @param accunt
* @param account
* @param user
*/
public void onComposing(String account, String user, CharSequence text) {
......@@ -295,8 +293,7 @@ public class ChatStateManager implements OnDisconnectListener,
}
@Override
public void onPacket(ConnectionItem connection, final String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, final String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem))
return;
final String resource = Jid.getResource(packet.getFrom());
......@@ -312,11 +309,10 @@ public class ChatStateManager implements OnDisconnectListener,
supports.remove(account, bareAddress, resource);
} else if (packet instanceof Message) {
boolean support = false;
for (PacketExtension extension : packet.getExtensions())
for (ExtensionElement extension : packet.getExtensions())
if (extension instanceof ChatStateExtension) {
removeCallback(account, bareAddress, resource);
ChatState chatState = ((ChatStateExtension) extension)
.getState();
ChatState chatState = ((ChatStateExtension) extension).getChatState();
chatStates.put(account, bareAddress, resource, chatState);
if (chatState != ChatState.active) {
Runnable runnable = new Runnable() {
......
......@@ -35,13 +35,16 @@ import com.xabber.android.data.notification.NotificationManager;
import com.xabber.android.data.roster.RosterManager;
import com.xabber.xmpp.muc.MUC;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.packet.MUCUser;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.muc.packet.MUCUser;
import java.util.ArrayList;
import java.util.Collection;
......@@ -294,7 +297,7 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
}
final MultiUserChat multiUserChat;
try {
multiUserChat = new MultiUserChat(xmppConnection, room);
multiUserChat = MultiUserChatManager.getInstanceFor(xmppConnection).getMultiUserChat(room);
} catch (IllegalStateException e) {
Application.getInstance().onError(R.string.NOT_CONNECTED);
return;
......@@ -324,7 +327,7 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
}
});
return;
} catch (final XMPPException e) {
} catch (final XMPPException.XMPPErrorException e) {
Application.getInstance().runOnUiThread(new Runnable() {
@Override
public void run() {
......@@ -333,13 +336,16 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
}
roomChat.setState(RoomState.error);
addAuthorizationError(account, room);
if (e.getXMPPError() != null && e.getXMPPError().getCode() == 409) {
Application.getInstance().onError(R.string.NICK_ALREADY_USED);
} else if (e.getXMPPError() != null && e.getXMPPError().getCode() == 401) {
Application.getInstance().onError(R.string.AUTHENTICATION_FAILED);
} else {
Application.getInstance().onError(R.string.NOT_CONNECTED);
}
XMPPError xmppError = e.getXMPPError();
if (xmppError != null && xmppError.getCondition() == XMPPError.Condition.conflict) {
Application.getInstance().onError(R.string.NICK_ALREADY_USED);
} else if (xmppError != null && xmppError.getCondition() == XMPPError.Condition.not_authorized) {
Application.getInstance().onError(R.string.AUTHENTICATION_FAILED);
} else {
Application.getInstance().onError(R.string.NOT_CONNECTED);
}
RosterManager.getInstance().onContactChanged(account, room);
}
});
......@@ -382,8 +388,8 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
public void run() {
try {
multiUserChat.leave();
} catch (IllegalStateException e) {
// Do nothing
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
};
......@@ -394,7 +400,7 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
}
@Override
public void onPacket(ConnectionItem connection, String bareAddress, Packet packet) {
public void onPacket(ConnectionItem connection, String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem)) {
return;
}
......@@ -439,7 +445,7 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
invite.setReason("");
mucUser.setInvite(invite);
message.addExtension(mucUser);
ConnectionManager.getInstance().sendPacket(account, message);
ConnectionManager.getInstance().sendStanza(account, message);
roomChat.putInvite(message.getPacketID(), user);
roomChat.newAction(roomChat.getNickname(), user, ChatAction.invite_sent);
}
......@@ -464,9 +470,10 @@ public class MUCManager implements OnLoadListener, OnPacketListener {
@Override
public void run() {
Collection<HostedRoom> hostedRooms = null;
try {
hostedRooms = MultiUserChat.getHostedRooms(xmppConnection, serviceName);
} catch (XMPPException e) {
hostedRooms = MultiUserChatManager.getInstanceFor(xmppConnection).getHostedRooms(serviceName);
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException | SmackException.NotConnectedException e) {
e.printStackTrace();
}
......
......@@ -32,11 +32,12 @@ import com.xabber.xmpp.muc.Role;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.packet.MUCUser;
import org.jivesoftware.smackx.muc.packet.MUCItem;
import org.jivesoftware.smackx.muc.packet.MUCUser;
import org.jxmpp.util.XmppStringUtils;
import java.util.Collection;
import java.util.Collections;
......@@ -180,12 +181,12 @@ public class RoomChat extends AbstractChat {
}
@Override
protected boolean onPacket(String bareAddress, Packet packet) {
protected boolean onPacket(String bareAddress, Stanza packet) {
if (!super.onPacket(bareAddress, packet)) {
return false;
}
final String from = packet.getFrom();
final String resource = StringUtils.parseResource(from);
final String resource = XmppStringUtils.parseResource(from);
if (packet instanceof Message) {
final Message message = (Message) packet;
if (message.getType() == Message.Type.error) {
......@@ -200,7 +201,7 @@ public class RoomChat extends AbstractChat {
onInvitationDeclined(mucUser.getDecline().getFrom(), mucUser.getDecline().getReason());
return true;
}
if (mucUser != null && mucUser.getStatus() != null && mucUser.getStatus().getCode().equals("100")
if (mucUser != null && mucUser.getStatus() != null && mucUser.getStatus().contains(MUCUser.Status.create("100"))
&& ChatManager.getInstance().isSuppress100(account, user)) {
// 'This room is not anonymous'
return true;
......@@ -280,12 +281,11 @@ public class RoomChat extends AbstractChat {
occupants.remove(stringPrep);
MUCUser mucUser = MUC.getMUCUserExtension(presence);
if (mucUser != null && mucUser.getStatus() != null) {
String code = mucUser.getStatus().getCode();
if ("307".equals(code)) {
if (mucUser.getStatus().contains(MUCUser.Status.KICKED_307)) {
onKick(resource, mucUser.getItem().getActor());
} else if ("301".equals(code)) {
} else if (mucUser.getStatus().contains(MUCUser.Status.BANNED_301)){
onBan(resource, mucUser.getItem().getActor());
} else if ("303".equals(code)) {
} else if (mucUser.getStatus().contains(MUCUser.Status.NEW_NICKNAME_303)) {
String newNick = mucUser.getItem().getNick();
if (newNick == null) {
return true;
......@@ -293,7 +293,7 @@ public class RoomChat extends AbstractChat {
onRename(resource, newNick);
Occupant occupant = createOccupant(newNick, presence);
occupants.put(Jid.getStringPrep(newNick), occupant);
} else if ("321".equals(code)) {
} else if (mucUser.getStatus().contains(MUCUser.Status.REMOVED_AFFIL_CHANGE_321)) {
onRevoke(resource, mucUser.getItem().getActor());
}
} else {
......@@ -368,15 +368,15 @@ public class RoomChat extends AbstractChat {
String statusText = null;
MUCUser mucUser = MUC.getMUCUserExtension(presence);
if (mucUser != null) {
MUCUser.Item item = mucUser.getItem();
MUCItem item = mucUser.getItem();
if (item != null) {
jid = item.getJid();
try {
affiliation = Affiliation.fromString(item.getAffiliation());
affiliation = Affiliation.fromString(item.getAffiliation().toString());
} catch (NoSuchElementException e) {
}
try {
role = Role.fromString(item.getRole());
role = Role.fromString(item.getRole().toString());
} catch (NoSuchElementException e) {
}
statusMode = StatusMode.createStatusMode(presence);
......
......@@ -235,7 +235,7 @@ public class OTRManager implements OtrEngineHost, OtrEngineListener,
SSNManager.getInstance().setSessionOtrMode(account, user, abstractChat.getThreadId(), OtrMode.prefer);
try {
ConnectionManager.getInstance()
.sendPacket(abstractChat.getAccount(), abstractChat.createMessagePacket(msg));
.sendStanza(abstractChat.getAccount(), abstractChat.createMessagePacket(msg));
} catch (NetworkException e) {
throw new OtrException(e);
}
......
......@@ -14,13 +14,6 @@
*/
package com.xabber.android.data.extension.ping;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.Ping;
import com.xabber.android.data.Application;
import com.xabber.android.data.LogManager;
import com.xabber.android.data.NetworkException;
......@@ -29,6 +22,14 @@ import com.xabber.android.data.connection.ConnectionItem;
import com.xabber.android.data.connection.ConnectionManager;
import com.xabber.android.data.connection.OnPacketListener;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.ping.packet.Ping;
/**
* Reply on incoming ping requests.
*
......@@ -41,15 +42,13 @@ public class PingManager implements OnPacketListener {
static {
instance = new PingManager();
Application.getInstance().addManager(instance);
Connection
.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final Connection connection) {
ServiceDiscoveryManager.getInstanceFor(connection)
.addFeature("urn:xmpp:ping");
}
});
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final XMPPConnection connection) {
ServiceDiscoveryManager.getInstanceFor(connection)
.addFeature("urn:xmpp:ping");
}
});
}
public static PingManager getInstance() {
......@@ -60,18 +59,17 @@ public class PingManager implements OnPacketListener {
}
@Override
public void onPacket(ConnectionItem connection, final String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, final String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem))
return;
final String account = ((AccountItem) connection).getAccount();
if (!(packet instanceof Ping))
return;
final Ping ping = (Ping) packet;
if (ping.getType() != IQ.Type.GET)
if (ping.getType() != IQ.Type.get)
return;
try {
ConnectionManager.getInstance().sendPacket(account,
ConnectionManager.getInstance().sendStanza(account,
IQ.createResultIQ(ping));
} catch (NetworkException e) {
LogManager.exception(this, e);
......
......@@ -14,13 +14,6 @@
*/
package com.xabber.android.data.extension.ssn;
import java.util.Collection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.packet.DataForm;
import com.xabber.android.data.Application;
import com.xabber.android.data.NetworkException;
import com.xabber.android.data.account.AccountItem;
......@@ -40,6 +33,13 @@ import com.xabber.xmpp.ssn.Feature;
import com.xabber.xmpp.ssn.LoggingValue;
import com.xabber.xmpp.ssn.SecurityValue;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.xdata.packet.DataForm;
import java.util.Collection;
/**
* Stanza Session Negotiation.
* <p/>
......@@ -82,8 +82,7 @@ public class SSNManager implements OnPacketListener, OnAccountRemovedListener {
}
@Override
public void onPacket(ConnectionItem connection, final String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, final String bareAddress, Stanza packet) {
String from = packet.getFrom();
if (from == null)
return;
......@@ -95,7 +94,7 @@ public class SSNManager implements OnPacketListener, OnAccountRemovedListener {
String session = message.getThread();
if (session == null)
return;
for (PacketExtension packetExtension : packet.getExtensions())
for (ExtensionElement packetExtension : packet.getExtensions())
if (packetExtension instanceof Feature) {
Feature feature = (Feature) packetExtension;
if (!feature.isValid())
......@@ -293,7 +292,7 @@ public class SSNManager implements OnPacketListener, OnAccountRemovedListener {
message.setThread(session);
message.addExtension(feature);
try {
ConnectionManager.getInstance().sendPacket(account, message);
ConnectionManager.getInstance().sendStanza(account, message);
} catch (NetworkException e) {
}
}
......
......@@ -14,18 +14,6 @@
*/
package com.xabber.android.data.extension.time;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import com.xabber.android.data.Application;
import com.xabber.android.data.NetworkException;
import com.xabber.android.data.account.AccountItem;
......@@ -39,6 +27,19 @@ import com.xabber.android.data.extension.capability.ServerInfoManager;
import com.xabber.xmpp.address.Jid;
import com.xabber.xmpp.time.Time;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Manage server time and response with local time.
*
......@@ -65,14 +66,12 @@ public class TimeManager implements OnServerInfoReceivedListener,
instance = new TimeManager();
Application.getInstance().addManager(instance);
Connection
.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final Connection connection) {
ServiceDiscoveryManager.getInstanceFor(connection)
.addFeature(FEATURE);
}
});
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override
public void connectionCreated(final XMPPConnection connection) {
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(FEATURE);
}
});
}
public static TimeManager getInstance() {
......@@ -98,7 +97,7 @@ public class TimeManager implements OnServerInfoReceivedListener,
sents.put(account, new Date());
Time packet = new Time();
packet.setTo(Jid.getServer(account));
packet.setType(Type.GET);
packet.setType(Type.get);
try {
ConnectionManager.getInstance().sendRequest(account, packet,
this);
......@@ -110,17 +109,16 @@ public class TimeManager implements OnServerInfoReceivedListener,
}
@Override
public void onPacket(ConnectionItem connection, final String bareAddress,
Packet packet) {
public void onPacket(ConnectionItem connection, final String bareAddress, Stanza packet) {
if (!(connection instanceof AccountItem))
return;
String account = ((AccountItem) connection).getAccount();
if (!(packet instanceof Time))
return;
Time time = (Time) packet;
if (time.getType() == Type.GET) {
if (time.getType() == Type.get) {
Time result = new Time();
result.setType(Type.RESULT);
result.setType(Type.result);
result.setPacketID(time.getPacketID());
result.setFrom(time.getTo());
result.setTo(time.getFrom());
......@@ -129,7 +127,7 @@ public class TimeManager implements OnServerInfoReceivedListener,
.get(Calendar.DST_OFFSET)) / 60000);
result.setUtc(calendar.getTime());
try {
ConnectionManager.getInstance().sendPacket(account, result);
ConnectionManager.getInstance().sendStanza(account, result);
} catch (NetworkException e) {
}
}
......
......@@ -15,7 +15,7 @@
package com.xabber.android.data.extension.vcard;
import com.xabber.android.data.BaseUIListener;
import com.xabber.xmpp.vcard.VCard;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
/**
* Listener for vCard to be received.
......
package com.xabber.android.data.extension.vcard;
import com.xabber.android.data.BaseUIListener;
public interface OnVCardSaveListener extends BaseUIListener {
void onVCardSaveSuccess(String account);
void onVCardSaveFailed(String account);
}
......@@ -34,9 +34,9 @@ import com.xabber.xmpp.carbon.CarbonManager;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.DelayInformation;
import org.jivesoftware.smackx.delay.packet.DelayInformation;
import java.util.ArrayList;
import java.util.Collection;
......@@ -582,7 +582,7 @@ public abstract class AbstractChat extends BaseEntity {
.getTimestamp()));
try {
ConnectionManager.getInstance()
.sendPacket(account, message);
.sendStanza(account, message);
} catch (NetworkException e) {
break;
}
......@@ -659,7 +659,7 @@ public abstract class AbstractChat extends BaseEntity {
* @param packet
* @return Whether packet was directed to this chat.
*/
protected boolean onPacket(String bareAddress, Packet packet) {
protected boolean onPacket(String bareAddress, Stanza packet) {
return accept(bareAddress, packet.getFrom());
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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