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>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>

View File

@ -287,5 +287,6 @@ public class Contact {
public static final int PREEMPTIVE_GRANT = 4;
public static final int IN_ROSTER = 8;
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) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("xmppService",CREATE_CONTATCS_STATEMENT);
}
@Override

View File

@ -508,8 +508,12 @@ public class XmppConnectionService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
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();
return START_STICKY;
} else if ((intent!=null)&&(Intent.ACTION_SHUTDOWN.equals(intent.getAction()))){
logoutAndSave();
return START_NOT_STICKY;
}
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
@ -617,10 +621,15 @@ public class XmppConnectionService extends Service {
for (Account account : accounts) {
databaseBackend.writeRoster(account.getRoster());
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");
stopSelf();
}
protected void scheduleWakeupCall(int seconds, boolean ping) {
@ -1193,10 +1202,15 @@ public class XmppConnectionService extends Service {
}
public void pushContactToServer(Contact contact) {
Account account = contact.getAccount();
if (account.getStatus() == Account.STATUS_ONLINE) {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
iq.query("jabber:iq:roster").addChild(contact.asElement());
Account account = contact.getAccount();
account.getXmppConnection().sendIqPacket(iq, null);
contact.resetOption(Contact.Options.DIRTY_PUSH);
} else {
contact.setOption(Contact.Options.DIRTY_PUSH);
}
}
public void deleteContactOnServer(Contact contact) {

View File

@ -103,13 +103,17 @@ public class XmppConnection implements Runnable {
public XmppConnection(Account account, PowerManager pm) {
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();
}
protected void changeStatus(int 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;
}
if (nextStatus == Account.STATUS_ONLINE) {
@ -127,7 +131,8 @@ public class XmppConnection implements Runnable {
lastConnect = SystemClock.elapsedRealtime();
this.attempt++;
try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
shouldAuthenticate = shouldBind = !account
.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
packetCallbacks.clear();
@ -229,8 +234,7 @@ public class XmppConnection implements Runnable {
} else if (nextTag.isStart("compressed")) {
switchOverToZLib(nextTag);
} else if (nextTag.isStart("success")) {
Log.d(LOGTAG, account.getJid()
+ ": logged in");
Log.d(LOGTAG, account.getJid() + ": logged in");
tagReader.readTag();
tagReader.reset();
sendStartStream();
@ -242,17 +246,21 @@ public class XmppConnection implements Runnable {
} else if (nextTag.isStart("challenge")) {
String challange = tagReader.readElement(nextTag).getContent();
Element response = new Element("response");
response.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
response.setContent(CryptoHelper.saslDigestMd5(account, challange));
response.setAttribute("xmlns",
"urn:ietf:params:xml:ns:xmpp-sasl");
response.setContent(CryptoHelper.saslDigestMd5(account,
challange));
tagWriter.writeElement(response);
} else if (nextTag.isStart("enabled")) {
this.stanzasSent = 0;
Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) {
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 {
Log.d(LOGTAG,account.getJid()+": stream managment("+smVersion+") enabled");
Log.d(LOGTAG, account.getJid() + ": stream managment("
+ smVersion + ") enabled");
}
this.lastSessionStarted = SystemClock.elapsedRealtime();
this.stanzasReceived = 0;
@ -325,7 +333,8 @@ public class XmppConnection implements Runnable {
while (!nextTag.isEnd(element.getName())) {
if (!nextTag.isNo()) {
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.setAttributes(currentTag.getAttributes());
}
@ -348,7 +357,8 @@ public class XmppConnection implements Runnable {
if (packet instanceof JinglePacket) {
if (this.jingleListener != null) {
this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
this.jingleListener.onJinglePacketReceived(account,
(JinglePacket) packet);
}
} else {
if (packetCallbacks.containsKey(packet.getId())) {
@ -403,12 +413,15 @@ public class XmppConnection implements Runnable {
tagWriter.writeElement(compress);
}
private void switchOverToZLib(Tag currentTag) throws XmlPullParserException,
IOException, NoSuchAlgorithmException {
private void switchOverToZLib(Tag currentTag)
throws XmlPullParserException, IOException,
NoSuchAlgorithmException {
tagReader.readTag(); // read tag close
tagWriter.setOutputStream(new ZLibOutputStream(tagWriter.getOutputStream()));
tagReader.setInputStream(new ZLibInputStream(tagReader.getInputStream()));
tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
.getOutputStream()));
tagReader
.setInputStream(new ZLibInputStream(tagReader.getInputStream()));
sendStartStream();
Log.d(LOGTAG, account.getJid() + ": compression enabled");
@ -457,13 +470,15 @@ public class XmppConnection implements Runnable {
if (e.getCause() instanceof CertPathValidatorException) {
String sha;
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest sha1 = MessageDigest
.getInstance("SHA1");
sha1.update(chain[0].getEncoded());
sha = CryptoHelper.bytesToHex(sha1.digest());
if (!sha.equals(account.getSSLFingerprint())) {
changeStatus(Account.STATUS_TLS_ERROR);
if (tlsListener != null) {
tlsListener.onTLSExceptionReceived(sha,account);
tlsListener.onTLSExceptionReceived(sha,
account);
}
throw new CertificateException();
}
@ -528,21 +543,27 @@ public class XmppConnection implements Runnable {
sendStartTLS();
} else if (compressionAvailable()) {
sendCompressionZlib();
} else if (this.streamFeatures.hasChild("register")&&(account.isOptionSet(Account.OPTION_REGISTER))) {
} else if (this.streamFeatures.hasChild("register")
&& (account.isOptionSet(Account.OPTION_REGISTER))) {
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);
disconnect(true);
} else if (this.streamFeatures.hasChild("mechanisms")
&& shouldAuthenticate) {
List<String> mechanisms = extractMechanisms( streamFeatures.findChild("mechanisms"));
List<String> mechanisms = extractMechanisms(streamFeatures
.findChild("mechanisms"));
if (mechanisms.contains("PLAIN")) {
sendSaslAuthPlain();
} else if (mechanisms.contains("DIGEST-MD5")) {
sendSaslAuthDigestMd5();
}
} else if (this.streamFeatures.hasChild("sm","urn:xmpp:sm:"+smVersion) && streamId != null) {
ResumePacket resume = new ResumePacket(this.streamId,stanzasReceived,smVersion);
} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
+ smVersion)
&& streamId != null) {
ResumePacket resume = new ResumePacket(this.streamId,
stanzasReceived, smVersion);
this.tagWriter.writeStanzaAsync(resume);
} else if (this.streamFeatures.hasChild("bind") && shouldBind) {
sendBindRequest();
@ -550,13 +571,19 @@ public class XmppConnection implements Runnable {
}
private boolean compressionAvailable() {
if (!this.streamFeatures.hasChild("compression", "http://jabber.org/features/compress")) return false;
if (!ZLibOutputStream.SUPPORTED) return false;
if (!account.isOptionSet(Account.OPTION_USECOMPRESSION)) return false;
if (!this.streamFeatures.hasChild("compression",
"http://jabber.org/features/compress"))
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()) {
if (!"method".equals(child.getName())) continue;
if (!"method".equals(child.getName()))
continue;
if ("zlib".equalsIgnoreCase(child.getContent())) {
return true;
@ -566,7 +593,8 @@ public class XmppConnection implements Runnable {
}
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()) {
mechanisms.add(child.getContent());
}
@ -582,20 +610,27 @@ public class XmppConnection implements Runnable {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
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);
Element username = new Element("username").setContent(account.getUsername());
Element password = new Element("password").setContent(account.getPassword());
Element username = new Element("username")
.setContent(account.getUsername());
Element password = new Element("password")
.setContent(account.getPassword());
register.query("jabber:iq:register").addChild(username);
register.query().addChild(password);
sendIqPacket(register, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
public void onIqPacketReceived(Account account,
IqPacket packet) {
if (packet.getType() == IqPacket.TYPE_RESULT) {
account.setOption(Account.OPTION_REGISTER, false);
account.setOption(Account.OPTION_REGISTER,
false);
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);
} else {
changeStatus(Account.STATUS_REGISTRATION_FAILED);
@ -607,7 +642,9 @@ public class XmppConnection implements Runnable {
} else {
changeStatus(Account.STATUS_REGISTRATION_FAILED);
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 {
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() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
@ -643,7 +681,8 @@ public class XmppConnection implements Runnable {
if (this.streamFeatures.hasChild("session")) {
Log.d(LOGTAG, account.getJid() + ": sending deprecated session");
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);
}
}
@ -660,8 +699,7 @@ public class XmppConnection implements Runnable {
List<String> features = new ArrayList<String>();
for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("feature")) {
features.add(elements.get(i).getAttribute(
"var"));
features.add(elements.get(i).getAttribute("var"));
}
}
disco.put(server, features);
@ -690,8 +728,7 @@ public class XmppConnection implements Runnable {
List<Element> elements = packet.query().getChildren();
for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("item")) {
String jid = elements.get(i).getAttribute(
"jid");
String jid = elements.get(i).getAttribute("jid");
sendServiceDiscoveryInfo(jid);
}
}
@ -771,7 +808,8 @@ public class XmppConnection implements Runnable {
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;
++stanzasSent;
tagWriter.writeStanzaAsync(packet);
@ -809,7 +847,8 @@ public class XmppConnection implements Runnable {
this.presenceListener = listener;
}
public void setOnJinglePacketReceivedListener(OnJinglePacketReceived listener) {
public void setOnJinglePacketReceivedListener(
OnJinglePacketReceived listener) {
this.jingleListener = listener;
}
@ -817,7 +856,8 @@ public class XmppConnection implements Runnable {
this.statusListener = listener;
}
public void setOnTLSExceptionReceivedListener(OnTLSExceptionReceived listener) {
public void setOnTLSExceptionReceivedListener(
OnTLSExceptionReceived listener) {
this.tlsListener = listener;
}
@ -833,18 +873,28 @@ public class XmppConnection implements Runnable {
socket.close();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
if (tagWriter.isActive()) {
tagWriter.finish();
try {
while (!tagWriter.finished()) {
//Log.d(LOGTAG,"not yet finished");
Log.d(LOGTAG, "not yet finished");
Thread.sleep(100);
}
tagWriter.writeTag(Tag.end("stream:stream"));
}
} catch (IOException e) {
Log.d(LOGTAG, "io exception during disconnect");
} 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) {
Iterator<Entry<String, List<String>>> it = this.disco.entrySet().iterator();
Iterator<Entry<String, List<String>>> it = this.disco.entrySet()
.iterator();
while (it.hasNext()) {
Entry<String, List<String>> pairs = it.next();
if (pairs.getValue().contains(feature)) {