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) {
@ -127,7 +131,8 @@ public class XmppConnection implements Runnable {
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();
@ -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;
@ -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());
} }
@ -348,7 +357,8 @@ public class XmppConnection implements Runnable {
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,12 +413,15 @@ 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");
@ -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();
} }
@ -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,7 +593,8 @@ 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
.getChildren().size());
for (Element child : stream.getChildren()) { for (Element child : stream.getChildren()) {
mechanisms.add(child.getContent()); mechanisms.add(child.getContent());
} }
@ -582,20 +610,27 @@ 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,
IqPacket packet) {
if (packet.getType() == IqPacket.TYPE_RESULT) { if (packet.getType() == IqPacket.TYPE_RESULT) {
account.setOption(Account.OPTION_REGISTER, false); 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);
@ -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,7 +652,8 @@ 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) {
@ -643,7 +681,8 @@ 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);
} }
} }
@ -771,7 +808,8 @@ 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);
@ -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;
} }
@ -833,18 +873,28 @@ public class XmppConnection implements Runnable {
socket.close(); socket.close();
return; return;
} }
new Thread(new Runnable() {
@Override
public void run() {
if (tagWriter.isActive()) { if (tagWriter.isActive()) {
tagWriter.finish(); tagWriter.finish();
try {
while (!tagWriter.finished()) { while (!tagWriter.finished()) {
//Log.d(LOGTAG,"not yet 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");
} }
} }
@ -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)) {