write contacts on system shutdown

This commit is contained in:
Daniel Gultsch 2014-05-21 22:22:36 +02:00
parent a9d384875b
commit 1db807ef58
5 changed files with 198 additions and 132 deletions

View File

@ -32,6 +32,7 @@
<intent-filter> <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter> </intent-filter>
</receiver> </receiver>

View File

@ -287,5 +287,6 @@ public class Contact {
public static final int PREEMPTIVE_GRANT = 4; public static final int PREEMPTIVE_GRANT = 4;
public static final int IN_ROSTER = 8; public static final int IN_ROSTER = 8;
public static final int PENDING_SUBSCRIPTION_REQUEST = 16; public static final int PENDING_SUBSCRIPTION_REQUEST = 16;
public static final int DIRTY_PUSH = 32;
} }
} }

View File

@ -32,7 +32,6 @@ public class DatabaseBackend extends SQLiteOpenHelper {
public DatabaseBackend(Context context) { public DatabaseBackend(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("xmppService",CREATE_CONTATCS_STATEMENT);
} }
@Override @Override

View File

@ -508,8 +508,12 @@ public class XmppConnectionService extends Service {
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
this.wakeLock.acquire(); this.wakeLock.acquire();
if ((intent!=null)&&(intent.getAction()!=null)&&(intent.getAction().equals(ACTION_MERGE_PHONE_CONTACTS))) { if ((intent!=null)&&(ACTION_MERGE_PHONE_CONTACTS.equals(intent.getAction()))) {
mergePhoneContactsWithRoster(); mergePhoneContactsWithRoster();
return START_STICKY;
} else if ((intent!=null)&&(Intent.ACTION_SHUTDOWN.equals(intent.getAction()))){
logoutAndSave();
return START_NOT_STICKY;
} }
ConnectivityManager cm = (ConnectivityManager) getApplicationContext() ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE); .getSystemService(Context.CONNECTIVITY_SERVICE);
@ -617,10 +621,15 @@ public class XmppConnectionService extends Service {
for (Account account : accounts) { for (Account account : accounts) {
databaseBackend.writeRoster(account.getRoster()); databaseBackend.writeRoster(account.getRoster());
if (account.getXmppConnection() != null) { if (account.getXmppConnection() != null) {
disconnect(account, true); disconnect(account, false);
} }
} }
Context context = getApplicationContext();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, EventReceiver.class);
alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
Log.d(LOGTAG,"good bye"); Log.d(LOGTAG,"good bye");
stopSelf();
} }
protected void scheduleWakeupCall(int seconds, boolean ping) { protected void scheduleWakeupCall(int seconds, boolean ping) {
@ -1193,10 +1202,15 @@ public class XmppConnectionService extends Service {
} }
public void pushContactToServer(Contact contact) { public void pushContactToServer(Contact contact) {
Account account = contact.getAccount();
if (account.getStatus() == Account.STATUS_ONLINE) {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET); IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
iq.query("jabber:iq:roster").addChild(contact.asElement()); iq.query("jabber:iq:roster").addChild(contact.asElement());
Account account = contact.getAccount();
account.getXmppConnection().sendIqPacket(iq, null); account.getXmppConnection().sendIqPacket(iq, null);
contact.resetOption(Contact.Options.DIRTY_PUSH);
} else {
contact.setOption(Contact.Options.DIRTY_PUSH);
}
} }
public void deleteContactOnServer(Contact contact) { public void deleteContactOnServer(Contact contact) {

View File

@ -103,13 +103,17 @@ public class XmppConnection implements Runnable {
public XmppConnection(Account account, PowerManager pm) { public XmppConnection(Account account, PowerManager pm) {
this.account = account; this.account = account;
this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,account.getJid()); this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
account.getJid());
tagWriter = new TagWriter(); tagWriter = new TagWriter();
} }
protected void changeStatus(int nextStatus) { protected void changeStatus(int nextStatus) {
if (account.getStatus() != nextStatus) { if (account.getStatus() != nextStatus) {
if ((nextStatus == Account.STATUS_OFFLINE)&&(account.getStatus() != Account.STATUS_CONNECTING)&&(account.getStatus() != Account.STATUS_ONLINE)&&(account.getStatus() != Account.STATUS_DISABLED)) { if ((nextStatus == Account.STATUS_OFFLINE)
&& (account.getStatus() != Account.STATUS_CONNECTING)
&& (account.getStatus() != Account.STATUS_ONLINE)
&& (account.getStatus() != Account.STATUS_DISABLED)) {
return; return;
} }
if (nextStatus == Account.STATUS_ONLINE) { if (nextStatus == Account.STATUS_ONLINE) {
@ -123,18 +127,19 @@ public class XmppConnection implements Runnable {
} }
protected void connect() { protected void connect() {
Log.d(LOGTAG,account.getJid()+ ": connecting"); Log.d(LOGTAG, account.getJid() + ": connecting");
lastConnect = SystemClock.elapsedRealtime(); lastConnect = SystemClock.elapsedRealtime();
this.attempt++; this.attempt++;
try { try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER); shouldAuthenticate = shouldBind = !account
.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock); tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter(); tagWriter = new TagWriter();
packetCallbacks.clear(); packetCallbacks.clear();
this.changeStatus(Account.STATUS_CONNECTING); this.changeStatus(Account.STATUS_CONNECTING);
Bundle namePort = DNSHelper.getSRVRecord(account.getServer()); Bundle namePort = DNSHelper.getSRVRecord(account.getServer());
if ("timeout".equals(namePort.getString("error"))) { if ("timeout".equals(namePort.getString("error"))) {
Log.d(LOGTAG,account.getJid()+": dns timeout"); Log.d(LOGTAG, account.getJid() + ": dns timeout");
this.changeStatus(Account.STATUS_OFFLINE); this.changeStatus(Account.STATUS_OFFLINE);
return; return;
} }
@ -229,8 +234,7 @@ public class XmppConnection implements Runnable {
} else if (nextTag.isStart("compressed")) { } else if (nextTag.isStart("compressed")) {
switchOverToZLib(nextTag); switchOverToZLib(nextTag);
} else if (nextTag.isStart("success")) { } else if (nextTag.isStart("success")) {
Log.d(LOGTAG, account.getJid() Log.d(LOGTAG, account.getJid() + ": logged in");
+ ": logged in");
tagReader.readTag(); tagReader.readTag();
tagReader.reset(); tagReader.reset();
sendStartStream(); sendStartStream();
@ -242,17 +246,21 @@ public class XmppConnection implements Runnable {
} else if (nextTag.isStart("challenge")) { } else if (nextTag.isStart("challenge")) {
String challange = tagReader.readElement(nextTag).getContent(); String challange = tagReader.readElement(nextTag).getContent();
Element response = new Element("response"); Element response = new Element("response");
response.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl"); response.setAttribute("xmlns",
response.setContent(CryptoHelper.saslDigestMd5(account, challange)); "urn:ietf:params:xml:ns:xmpp-sasl");
response.setContent(CryptoHelper.saslDigestMd5(account,
challange));
tagWriter.writeElement(response); tagWriter.writeElement(response);
} else if (nextTag.isStart("enabled")) { } else if (nextTag.isStart("enabled")) {
this.stanzasSent = 0; this.stanzasSent = 0;
Element enabled = tagReader.readElement(nextTag); Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) { if ("true".equals(enabled.getAttribute("resume"))) {
this.streamId = enabled.getAttribute("id"); this.streamId = enabled.getAttribute("id");
Log.d(LOGTAG,account.getJid()+": stream managment("+smVersion+") enabled (resumable)"); Log.d(LOGTAG, account.getJid() + ": stream managment("
+ smVersion + ") enabled (resumable)");
} else { } else {
Log.d(LOGTAG,account.getJid()+": stream managment("+smVersion+") enabled"); Log.d(LOGTAG, account.getJid() + ": stream managment("
+ smVersion + ") enabled");
} }
this.lastSessionStarted = SystemClock.elapsedRealtime(); this.lastSessionStarted = SystemClock.elapsedRealtime();
this.stanzasReceived = 0; this.stanzasReceived = 0;
@ -260,26 +268,26 @@ public class XmppConnection implements Runnable {
tagWriter.writeStanzaAsync(r); tagWriter.writeStanzaAsync(r);
} else if (nextTag.isStart("resumed")) { } else if (nextTag.isStart("resumed")) {
lastPaketReceived = SystemClock.elapsedRealtime(); lastPaketReceived = SystemClock.elapsedRealtime();
Log.d(LOGTAG,account.getJid()+": session resumed"); Log.d(LOGTAG, account.getJid() + ": session resumed");
tagReader.readElement(nextTag); tagReader.readElement(nextTag);
sendPing(); sendPing();
changeStatus(Account.STATUS_ONLINE); changeStatus(Account.STATUS_ONLINE);
} else if (nextTag.isStart("r")) { } else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag); tagReader.readElement(nextTag);
AckPacket ack = new AckPacket(this.stanzasReceived,smVersion); AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
//Log.d(LOGTAG,ack.toString()); // Log.d(LOGTAG,ack.toString());
tagWriter.writeStanzaAsync(ack); tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) { } else if (nextTag.isStart("a")) {
Element ack = tagReader.readElement(nextTag); Element ack = tagReader.readElement(nextTag);
lastPaketReceived = SystemClock.elapsedRealtime(); lastPaketReceived = SystemClock.elapsedRealtime();
int serverSequence = Integer.parseInt(ack.getAttribute("h")); int serverSequence = Integer.parseInt(ack.getAttribute("h"));
if (serverSequence>this.stanzasSent) { if (serverSequence > this.stanzasSent) {
this.stanzasSent = serverSequence; this.stanzasSent = serverSequence;
} }
//Log.d(LOGTAG,"server ack"+ack.toString()+" ("+this.stanzasSent+")"); // Log.d(LOGTAG,"server ack"+ack.toString()+" ("+this.stanzasSent+")");
} else if (nextTag.isStart("failed")) { } else if (nextTag.isStart("failed")) {
tagReader.readElement(nextTag); tagReader.readElement(nextTag);
Log.d(LOGTAG,account.getJid()+": resumption failed"); Log.d(LOGTAG, account.getJid() + ": resumption failed");
streamId = null; streamId = null;
if (account.getStatus() != Account.STATUS_ONLINE) { if (account.getStatus() != Account.STATUS_ONLINE) {
sendBindRequest(); sendBindRequest();
@ -325,7 +333,8 @@ public class XmppConnection implements Runnable {
while (!nextTag.isEnd(element.getName())) { while (!nextTag.isEnd(element.getName())) {
if (!nextTag.isNo()) { if (!nextTag.isNo()) {
Element child = tagReader.readElement(nextTag); Element child = tagReader.readElement(nextTag);
if ((packetType == PACKET_IQ)&&("jingle".equals(child.getName()))) { if ((packetType == PACKET_IQ)
&& ("jingle".equals(child.getName()))) {
element = new JinglePacket(); element = new JinglePacket();
element.setAttributes(currentTag.getAttributes()); element.setAttributes(currentTag.getAttributes());
} }
@ -343,12 +352,13 @@ public class XmppConnection implements Runnable {
IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ); IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
if (packet.getId() == null) { if (packet.getId() == null) {
return; //an iq packet without id is definitely invalid return; // an iq packet without id is definitely invalid
} }
if (packet instanceof JinglePacket) { if (packet instanceof JinglePacket) {
if (this.jingleListener !=null) { if (this.jingleListener != null) {
this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet); this.jingleListener.onJinglePacketReceived(account,
(JinglePacket) packet);
} }
} else { } else {
if (packetCallbacks.containsKey(packet.getId())) { if (packetCallbacks.containsKey(packet.getId())) {
@ -403,15 +413,18 @@ public class XmppConnection implements Runnable {
tagWriter.writeElement(compress); tagWriter.writeElement(compress);
} }
private void switchOverToZLib(Tag currentTag) throws XmlPullParserException, private void switchOverToZLib(Tag currentTag)
IOException, NoSuchAlgorithmException { throws XmlPullParserException, IOException,
NoSuchAlgorithmException {
tagReader.readTag(); // read tag close tagReader.readTag(); // read tag close
tagWriter.setOutputStream(new ZLibOutputStream(tagWriter.getOutputStream())); tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
tagReader.setInputStream(new ZLibInputStream(tagReader.getInputStream())); .getOutputStream()));
tagReader
.setInputStream(new ZLibInputStream(tagReader.getInputStream()));
sendStartStream(); sendStartStream();
Log.d(LOGTAG,account.getJid()+": compression enabled"); Log.d(LOGTAG, account.getJid() + ": compression enabled");
processStream(tagReader.readTag()); processStream(tagReader.readTag());
} }
@ -457,13 +470,15 @@ public class XmppConnection implements Runnable {
if (e.getCause() instanceof CertPathValidatorException) { if (e.getCause() instanceof CertPathValidatorException) {
String sha; String sha;
try { try {
MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest sha1 = MessageDigest
.getInstance("SHA1");
sha1.update(chain[0].getEncoded()); sha1.update(chain[0].getEncoded());
sha = CryptoHelper.bytesToHex(sha1.digest()); sha = CryptoHelper.bytesToHex(sha1.digest());
if (!sha.equals(account.getSSLFingerprint())) { if (!sha.equals(account.getSSLFingerprint())) {
changeStatus(Account.STATUS_TLS_ERROR); changeStatus(Account.STATUS_TLS_ERROR);
if (tlsListener!=null) { if (tlsListener != null) {
tlsListener.onTLSExceptionReceived(sha,account); tlsListener.onTLSExceptionReceived(sha,
account);
} }
throw new CertificateException(); throw new CertificateException();
} }
@ -491,7 +506,7 @@ public class XmppConnection implements Runnable {
tagReader.setInputStream(sslSocket.getInputStream()); tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream()); tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream(); sendStartStream();
Log.d(LOGTAG,account.getJid()+": TLS connection established"); Log.d(LOGTAG, account.getJid() + ": TLS connection established");
processStream(tagReader.readTag()); processStream(tagReader.readTag());
sslSocket.close(); sslSocket.close();
} catch (NoSuchAlgorithmException e1) { } catch (NoSuchAlgorithmException e1) {
@ -528,21 +543,27 @@ public class XmppConnection implements Runnable {
sendStartTLS(); sendStartTLS();
} else if (compressionAvailable()) { } else if (compressionAvailable()) {
sendCompressionZlib(); sendCompressionZlib();
} else if (this.streamFeatures.hasChild("register")&&(account.isOptionSet(Account.OPTION_REGISTER))) { } else if (this.streamFeatures.hasChild("register")
&& (account.isOptionSet(Account.OPTION_REGISTER))) {
sendRegistryRequest(); sendRegistryRequest();
} else if (!this.streamFeatures.hasChild("register")&&(account.isOptionSet(Account.OPTION_REGISTER))) { } else if (!this.streamFeatures.hasChild("register")
&& (account.isOptionSet(Account.OPTION_REGISTER))) {
changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED); changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
disconnect(true); disconnect(true);
} else if (this.streamFeatures.hasChild("mechanisms") } else if (this.streamFeatures.hasChild("mechanisms")
&& shouldAuthenticate) { && shouldAuthenticate) {
List<String> mechanisms = extractMechanisms( streamFeatures.findChild("mechanisms")); List<String> mechanisms = extractMechanisms(streamFeatures
.findChild("mechanisms"));
if (mechanisms.contains("PLAIN")) { if (mechanisms.contains("PLAIN")) {
sendSaslAuthPlain(); sendSaslAuthPlain();
} else if (mechanisms.contains("DIGEST-MD5")) { } else if (mechanisms.contains("DIGEST-MD5")) {
sendSaslAuthDigestMd5(); sendSaslAuthDigestMd5();
} }
} else if (this.streamFeatures.hasChild("sm","urn:xmpp:sm:"+smVersion) && streamId != null) { } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
ResumePacket resume = new ResumePacket(this.streamId,stanzasReceived,smVersion); + smVersion)
&& streamId != null) {
ResumePacket resume = new ResumePacket(this.streamId,
stanzasReceived, smVersion);
this.tagWriter.writeStanzaAsync(resume); this.tagWriter.writeStanzaAsync(resume);
} else if (this.streamFeatures.hasChild("bind") && shouldBind) { } else if (this.streamFeatures.hasChild("bind") && shouldBind) {
sendBindRequest(); sendBindRequest();
@ -550,13 +571,19 @@ public class XmppConnection implements Runnable {
} }
private boolean compressionAvailable() { private boolean compressionAvailable() {
if (!this.streamFeatures.hasChild("compression", "http://jabber.org/features/compress")) return false; if (!this.streamFeatures.hasChild("compression",
if (!ZLibOutputStream.SUPPORTED) return false; "http://jabber.org/features/compress"))
if (!account.isOptionSet(Account.OPTION_USECOMPRESSION)) return false; return false;
if (!ZLibOutputStream.SUPPORTED)
return false;
if (!account.isOptionSet(Account.OPTION_USECOMPRESSION))
return false;
Element compression = this.streamFeatures.findChild("compression", "http://jabber.org/features/compress"); Element compression = this.streamFeatures.findChild("compression",
"http://jabber.org/features/compress");
for (Element child : compression.getChildren()) { for (Element child : compression.getChildren()) {
if (!"method".equals(child.getName())) continue; if (!"method".equals(child.getName()))
continue;
if ("zlib".equalsIgnoreCase(child.getContent())) { if ("zlib".equalsIgnoreCase(child.getContent())) {
return true; return true;
@ -566,8 +593,9 @@ public class XmppConnection implements Runnable {
} }
private List<String> extractMechanisms(Element stream) { private List<String> extractMechanisms(Element stream) {
ArrayList<String> mechanisms = new ArrayList<String>(stream.getChildren().size()); ArrayList<String> mechanisms = new ArrayList<String>(stream
for(Element child : stream.getChildren()) { .getChildren().size());
for (Element child : stream.getChildren()) {
mechanisms.add(child.getContent()); mechanisms.add(child.getContent());
} }
return mechanisms; return mechanisms;
@ -582,24 +610,31 @@ public class XmppConnection implements Runnable {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
Element instructions = packet.query().findChild("instructions"); Element instructions = packet.query().findChild("instructions");
if (packet.query().hasChild("username")&&(packet.query().hasChild("password"))) { if (packet.query().hasChild("username")
&& (packet.query().hasChild("password"))) {
IqPacket register = new IqPacket(IqPacket.TYPE_SET); IqPacket register = new IqPacket(IqPacket.TYPE_SET);
Element username = new Element("username").setContent(account.getUsername()); Element username = new Element("username")
Element password = new Element("password").setContent(account.getPassword()); .setContent(account.getUsername());
Element password = new Element("password")
.setContent(account.getPassword());
register.query("jabber:iq:register").addChild(username); register.query("jabber:iq:register").addChild(username);
register.query().addChild(password); register.query().addChild(password);
sendIqPacket(register, new OnIqPacketReceived() { sendIqPacket(register, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account,
if (packet.getType()==IqPacket.TYPE_RESULT) { IqPacket packet) {
account.setOption(Account.OPTION_REGISTER, false); if (packet.getType() == IqPacket.TYPE_RESULT) {
account.setOption(Account.OPTION_REGISTER,
false);
changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL); changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
} else if (packet.hasChild("error")&&(packet.findChild("error").hasChild("conflict"))){ } else if (packet.hasChild("error")
&& (packet.findChild("error")
.hasChild("conflict"))) {
changeStatus(Account.STATUS_REGISTRATION_CONFLICT); changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
} else { } else {
changeStatus(Account.STATUS_REGISTRATION_FAILED); changeStatus(Account.STATUS_REGISTRATION_FAILED);
Log.d(LOGTAG,packet.toString()); Log.d(LOGTAG, packet.toString());
} }
disconnect(true); disconnect(true);
} }
@ -607,7 +642,9 @@ public class XmppConnection implements Runnable {
} else { } else {
changeStatus(Account.STATUS_REGISTRATION_FAILED); changeStatus(Account.STATUS_REGISTRATION_FAILED);
disconnect(true); disconnect(true);
Log.d(LOGTAG,account.getJid()+": could not register. instructions are"+instructions.getContent()); Log.d(LOGTAG, account.getJid()
+ ": could not register. instructions are"
+ instructions.getContent());
} }
} }
}); });
@ -615,25 +652,26 @@ public class XmppConnection implements Runnable {
private void sendBindRequest() throws IOException { private void sendBindRequest() throws IOException {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET); IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind").addChild("resource").setContent(account.getResource()); iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
.addChild("resource").setContent(account.getResource());
this.sendUnboundIqPacket(iq, new OnIqPacketReceived() { this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
String resource = packet.findChild("bind").findChild("jid") String resource = packet.findChild("bind").findChild("jid")
.getContent().split("/")[1]; .getContent().split("/")[1];
account.setResource(resource); account.setResource(resource);
if (streamFeatures.hasChild("sm","urn:xmpp:sm:3")) { if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
smVersion = 3; smVersion = 3;
EnablePacket enable = new EnablePacket(smVersion); EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable); tagWriter.writeStanzaAsync(enable);
} else if (streamFeatures.hasChild("sm","urn:xmpp:sm:2")) { } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
smVersion = 2; smVersion = 2;
EnablePacket enable = new EnablePacket(smVersion); EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable); tagWriter.writeStanzaAsync(enable);
} }
sendServiceDiscoveryInfo(account.getServer()); sendServiceDiscoveryInfo(account.getServer());
sendServiceDiscoveryItems(account.getServer()); sendServiceDiscoveryItems(account.getServer());
if (bindListener !=null) { if (bindListener != null) {
bindListener.onBind(account); bindListener.onBind(account);
} }
@ -641,9 +679,10 @@ public class XmppConnection implements Runnable {
} }
}); });
if (this.streamFeatures.hasChild("session")) { if (this.streamFeatures.hasChild("session")) {
Log.d(LOGTAG,account.getJid()+": sending deprecated session"); Log.d(LOGTAG, account.getJid() + ": sending deprecated session");
IqPacket startSession = new IqPacket(IqPacket.TYPE_SET); IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
startSession.addChild("session","urn:ietf:params:xml:ns:xmpp-session"); startSession.addChild("session",
"urn:ietf:params:xml:ns:xmpp-session");
this.sendUnboundIqPacket(startSession, null); this.sendUnboundIqPacket(startSession, null);
} }
} }
@ -660,8 +699,7 @@ public class XmppConnection implements Runnable {
List<String> features = new ArrayList<String>(); List<String> features = new ArrayList<String>();
for (int i = 0; i < elements.size(); ++i) { for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("feature")) { if (elements.get(i).getName().equals("feature")) {
features.add(elements.get(i).getAttribute( features.add(elements.get(i).getAttribute("var"));
"var"));
} }
} }
disco.put(server, features); disco.put(server, features);
@ -690,8 +728,7 @@ public class XmppConnection implements Runnable {
List<Element> elements = packet.query().getChildren(); List<Element> elements = packet.query().getChildren();
for (int i = 0; i < elements.size(); ++i) { for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("item")) { if (elements.get(i).getName().equals("item")) {
String jid = elements.get(i).getAttribute( String jid = elements.get(i).getAttribute("jid");
"jid");
sendServiceDiscoveryInfo(jid); sendServiceDiscoveryInfo(jid);
} }
} }
@ -701,7 +738,7 @@ public class XmppConnection implements Runnable {
private void sendEnableCarbons() { private void sendEnableCarbons() {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET); IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
iq.addChild("enable","urn:xmpp:carbons:2"); iq.addChild("enable", "urn:xmpp:carbons:2");
this.sendIqPacket(iq, new OnIqPacketReceived() { this.sendIqPacket(iq, new OnIqPacketReceived() {
@Override @Override
@ -737,7 +774,7 @@ public class XmppConnection implements Runnable {
} }
public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) { public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
if (packet.getId()==null) { if (packet.getId() == null) {
String id = nextRandomId(); String id = nextRandomId();
packet.setAttribute("id", id); packet.setAttribute("id", id);
} }
@ -746,7 +783,7 @@ public class XmppConnection implements Runnable {
} }
public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) { public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) {
if (packet.getId()==null) { if (packet.getId() == null) {
String id = nextRandomId(); String id = nextRandomId();
packet.setAttribute("id", id); packet.setAttribute("id", id);
} }
@ -771,12 +808,13 @@ public class XmppConnection implements Runnable {
this.sendPacket(packet, callback); this.sendPacket(packet, callback);
} }
private synchronized void sendPacket(final AbstractStanza packet, PacketReceived callback) { private synchronized void sendPacket(final AbstractStanza packet,
PacketReceived callback) {
// TODO dont increment stanza count if packet = request packet or ack; // TODO dont increment stanza count if packet = request packet or ack;
++stanzasSent; ++stanzasSent;
tagWriter.writeStanzaAsync(packet); tagWriter.writeStanzaAsync(packet);
if (callback != null) { if (callback != null) {
if (packet.getId()==null) { if (packet.getId() == null) {
packet.setId(nextRandomId()); packet.setId(nextRandomId());
} }
packetCallbacks.put(packet.getId(), callback); packetCallbacks.put(packet.getId(), callback);
@ -789,7 +827,7 @@ public class XmppConnection implements Runnable {
} else { } else {
IqPacket iq = new IqPacket(IqPacket.TYPE_GET); IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
iq.setFrom(account.getFullJid()); iq.setFrom(account.getFullJid());
iq.addChild("ping","urn:xmpp:ping"); iq.addChild("ping", "urn:xmpp:ping");
this.sendIqPacket(iq, null); this.sendIqPacket(iq, null);
} }
} }
@ -809,7 +847,8 @@ public class XmppConnection implements Runnable {
this.presenceListener = listener; this.presenceListener = listener;
} }
public void setOnJinglePacketReceivedListener(OnJinglePacketReceived listener) { public void setOnJinglePacketReceivedListener(
OnJinglePacketReceived listener) {
this.jingleListener = listener; this.jingleListener = listener;
} }
@ -817,7 +856,8 @@ public class XmppConnection implements Runnable {
this.statusListener = listener; this.statusListener = listener;
} }
public void setOnTLSExceptionReceivedListener(OnTLSExceptionReceived listener) { public void setOnTLSExceptionReceivedListener(
OnTLSExceptionReceived listener) {
this.tlsListener = listener; this.tlsListener = listener;
} }
@ -827,29 +867,39 @@ public class XmppConnection implements Runnable {
public void disconnect(boolean force) { public void disconnect(boolean force) {
changeStatus(Account.STATUS_OFFLINE); changeStatus(Account.STATUS_OFFLINE);
Log.d(LOGTAG,"disconnecting"); Log.d(LOGTAG, "disconnecting");
try { try {
if (force) { if (force) {
socket.close(); socket.close();
return; return;
} }
new Thread(new Runnable() {
@Override
public void run() {
if (tagWriter.isActive()) { if (tagWriter.isActive()) {
tagWriter.finish(); tagWriter.finish();
while(!tagWriter.finished()) { try {
//Log.d(LOGTAG,"not yet finished"); while (!tagWriter.finished()) {
Log.d(LOGTAG, "not yet finished");
Thread.sleep(100); Thread.sleep(100);
} }
tagWriter.writeTag(Tag.end("stream:stream")); tagWriter.writeTag(Tag.end("stream:stream"));
}
} catch (IOException e) { } catch (IOException e) {
Log.d(LOGTAG,"io exception during disconnect"); Log.d(LOGTAG, "io exception during disconnect");
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(LOGTAG,"interupted while waiting for disconnect"); Log.d(LOGTAG, "interrupted");
}
}
}
});
} catch (IOException e) {
Log.d(LOGTAG, "io exception during disconnect");
} }
} }
public boolean hasFeatureRosterManagment() { public boolean hasFeatureRosterManagment() {
if (this.streamFeatures==null) { if (this.streamFeatures == null) {
return false; return false;
} else { } else {
return this.streamFeatures.hasChild("ver"); return this.streamFeatures.hasChild("ver");
@ -857,7 +907,7 @@ public class XmppConnection implements Runnable {
} }
public boolean hasFeatureStreamManagment() { public boolean hasFeatureStreamManagment() {
if (this.streamFeatures==null) { if (this.streamFeatures == null) {
return false; return false;
} else { } else {
return this.streamFeatures.hasChild("sm"); return this.streamFeatures.hasChild("sm");
@ -876,7 +926,8 @@ public class XmppConnection implements Runnable {
} }
public String findDiscoItemByFeature(String feature) { public String findDiscoItemByFeature(String feature) {
Iterator<Entry<String, List<String>>> it = this.disco.entrySet().iterator(); Iterator<Entry<String, List<String>>> it = this.disco.entrySet()
.iterator();
while (it.hasNext()) { while (it.hasNext()) {
Entry<String, List<String>> pairs = it.next(); Entry<String, List<String>> pairs = it.next();
if (pairs.getValue().contains(feature)) { if (pairs.getValue().contains(feature)) {
@ -904,7 +955,7 @@ public class XmppConnection implements Runnable {
} }
public int getTimeToNextAttempt() { public int getTimeToNextAttempt() {
int interval = (int) (25 * Math.pow(1.5,attempt)); int interval = (int) (25 * Math.pow(1.5, attempt));
int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000); int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
return interval - secondsSinceLast; return interval - secondsSinceLast;
} }