Merge branch 'development'

This commit is contained in:
Daniel Gultsch 2015-06-23 12:15:18 +02:00
commit 2dd16a8b56
68 changed files with 994 additions and 812 deletions

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="48"
height="48"
viewBox="0 0 48 48"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="ic_send_picture_away.svg">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1916"
inkscape:window-height="1036"
id="namedview6"
showgrid="false"
inkscape:zoom="4.9166667"
inkscape:cx="6.5084746"
inkscape:cy="24"
inkscape:window-x="0"
inkscape:window-y="20"
inkscape:window-maximized="0"
inkscape:current-layer="svg2" />
<path
d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"
id="path4"
style="fill:#ff9800;fill-opacity:0.627451" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="48"
height="48"
viewBox="0 0 48 48"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="ic_send_picture_dnd.svg">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1916"
inkscape:window-height="1036"
id="namedview6"
showgrid="false"
inkscape:zoom="4.9166667"
inkscape:cx="6.5084746"
inkscape:cy="24"
inkscape:window-x="0"
inkscape:window-y="20"
inkscape:window-maximized="0"
inkscape:current-layer="svg2" />
<path
d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"
id="path4"
style="fill:#f44336;fill-opacity:0.627451" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="48"
height="48"
viewBox="0 0 48 48"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="ic_send_picture_offline.svg">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1916"
inkscape:window-height="1036"
id="namedview6"
showgrid="false"
inkscape:zoom="4.9166667"
inkscape:cx="6.5084746"
inkscape:cy="24"
inkscape:window-x="0"
inkscape:window-y="20"
inkscape:window-maximized="0"
inkscape:current-layer="svg2" />
<path
d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"
id="path4"
style="fill:#000000;fill-opacity:0.627451" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="48"
height="48"
viewBox="0 0 48 48"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="ic_send_picture_online.svg">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1916"
inkscape:window-height="1036"
id="namedview6"
showgrid="false"
inkscape:zoom="4.9166667"
inkscape:cx="6.5084746"
inkscape:cy="24"
inkscape:window-x="0"
inkscape:window-y="20"
inkscape:window-maximized="0"
inkscape:current-layer="svg2" />
<path
d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"
id="path4"
style="fill:#259b24;fill-opacity:0.627451" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -30,6 +30,10 @@ images = {
'ic_send_cancel_offline.svg' => ['ic_send_cancel_offline', 36], 'ic_send_cancel_offline.svg' => ['ic_send_cancel_offline', 36],
'ic_send_cancel_away.svg' => ['ic_send_cancel_away', 36], 'ic_send_cancel_away.svg' => ['ic_send_cancel_away', 36],
'ic_send_cancel_dnd.svg' => ['ic_send_cancel_dnd', 36], 'ic_send_cancel_dnd.svg' => ['ic_send_cancel_dnd', 36],
'ic_send_picture_online.svg' => ['ic_send_picture_online', 36],
'ic_send_picture_offline.svg' => ['ic_send_picture_offline', 36],
'ic_send_picture_away.svg' => ['ic_send_picture_away', 36],
'ic_send_picture_dnd.svg' => ['ic_send_picture_dnd', 36]
} }
images.each do |source, result| images.each do |source, result|
resolutions.each do |name, factor| resolutions.each do |name, factor|

View File

@ -6,7 +6,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:1.0.1' classpath 'com.android.tools.build:gradle:1.2.3'
} }
} }
@ -35,6 +35,7 @@ dependencies {
compile 'com.google.zxing:android-integration:3.1.0' compile 'com.google.zxing:android-integration:3.1.0'
compile 'de.measite.minidns:minidns:0.1.3' compile 'de.measite.minidns:minidns:0.1.3'
compile 'de.timroes.android:EnhancedListView:0.3.4' compile 'de.timroes.android:EnhancedListView:0.3.4'
compile 'me.leolin:ShortcutBadger:1.1.1@aar'
} }
android { android {

View File

@ -3,7 +3,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:0.7.+' classpath 'com.android.tools.build:gradle:1.2.3'
} }
} }

View File

@ -5,7 +5,7 @@ buildscript {
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:0.12.2' classpath 'com.android.tools.build:gradle:1.2.3'
} }
} }

View File

@ -36,14 +36,14 @@ import net.java.otr4j.session.InstanceTag;
import net.java.otr4j.session.SessionID; import net.java.otr4j.session.SessionID;
import net.java.otr4j.session.FragmenterInstructions; import net.java.otr4j.session.FragmenterInstructions;
public class OtrEngine extends OtrCryptoEngineImpl implements OtrEngineHost { public class OtrService extends OtrCryptoEngineImpl implements OtrEngineHost {
private Account account; private Account account;
private OtrPolicy otrPolicy; private OtrPolicy otrPolicy;
private KeyPair keyPair; private KeyPair keyPair;
private XmppConnectionService mXmppConnectionService; private XmppConnectionService mXmppConnectionService;
public OtrEngine(XmppConnectionService service, Account account) { public OtrService(XmppConnectionService service, Account account) {
this.account = account; this.account = account;
this.otrPolicy = new OtrPolicyImpl(); this.otrPolicy = new OtrPolicyImpl();
this.otrPolicy.setAllowV1(false); this.otrPolicy.setAllowV1(false);
@ -285,7 +285,7 @@ public class OtrEngine extends OtrCryptoEngineImpl implements OtrEngineHost {
@Override @Override
public void verify(SessionID id, String fingerprint, boolean approved) { public void verify(SessionID id, String fingerprint, boolean approved) {
Log.d(Config.LOGTAG,"OtrEngine.verify("+id.toString()+","+fingerprint+","+String.valueOf(approved)+")"); Log.d(Config.LOGTAG,"OtrService.verify("+id.toString()+","+fingerprint+","+String.valueOf(approved)+")");
try { try {
final Jid jid = Jid.fromSessionID(id); final Jid jid = Jid.fromSessionID(id);
Conversation conversation = this.mXmppConnectionService.find(this.account,jid); Conversation conversation = this.mXmppConnectionService.find(this.account,jid);

View File

@ -19,7 +19,7 @@ import java.util.concurrent.CopyOnWriteArraySet;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.OtrEngine; import eu.siacs.conversations.crypto.OtrService;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.InvalidJidException;
@ -117,7 +117,7 @@ public class Account extends AbstractEntity {
protected JSONObject keys = new JSONObject(); protected JSONObject keys = new JSONObject();
protected String avatar; protected String avatar;
protected boolean online = false; protected boolean online = false;
private OtrEngine otrEngine = null; private OtrService mOtrService = null;
private XmppConnection xmppConnection = null; private XmppConnection xmppConnection = null;
private long mEndGracePeriod = 0L; private long mEndGracePeriod = 0L;
private String otrFingerprint; private String otrFingerprint;
@ -273,12 +273,12 @@ public class Account extends AbstractEntity {
return values; return values;
} }
public void initOtrEngine(final XmppConnectionService context) { public void initAccountServices(final XmppConnectionService context) {
this.otrEngine = new OtrEngine(context, this); this.mOtrService = new OtrService(context, this);
} }
public OtrEngine getOtrEngine() { public OtrService getOtrService() {
return this.otrEngine; return this.mOtrService;
} }
public XmppConnection getXmppConnection() { public XmppConnection getXmppConnection() {
@ -292,10 +292,10 @@ public class Account extends AbstractEntity {
public String getOtrFingerprint() { public String getOtrFingerprint() {
if (this.otrFingerprint == null) { if (this.otrFingerprint == null) {
try { try {
if (this.otrEngine == null) { if (this.mOtrService == null) {
return null; return null;
} }
final PublicKey publicKey = this.otrEngine.getPublicKey(); final PublicKey publicKey = this.mOtrService.getPublicKey();
if (publicKey == null || !(publicKey instanceof DSAPublicKey)) { if (publicKey == null || !(publicKey instanceof DSAPublicKey)) {
return null; return null;
} }

View File

@ -75,12 +75,7 @@ public class Bookmark extends Element implements ListItem {
} }
public String getNick() { public String getNick() {
Element nick = this.findChild("nick"); return this.findChildContent("nick");
if (nick != null) {
return nick.getContent();
} else {
return null;
}
} }
public void setNick(String nick) { public void setNick(String nick) {
@ -96,12 +91,7 @@ public class Bookmark extends Element implements ListItem {
} }
public String getPassword() { public String getPassword() {
Element password = this.findChild("password"); return this.findChildContent("password");
if (password != null) {
return password.getContent();
} else {
return null;
}
} }
public void setPassword(String password) { public void setPassword(String password) {

View File

@ -237,8 +237,16 @@ public class Contact implements ListItem, Blockable {
return this.presences.getMostAvailableStatus(); return this.presences.getMostAvailableStatus();
} }
public void setPhotoUri(String uri) { public boolean setPhotoUri(String uri) {
if (uri != null && !uri.equals(this.photoUri)) {
this.photoUri = uri; this.photoUri = uri;
return true;
} else if (this.photoUri != null && uri == null) {
this.photoUri = null;
return true;
} else {
return false;
}
} }
public void setServerName(String serverName) { public void setServerName(String serverName) {

View File

@ -249,6 +249,12 @@ public class Conversation extends AbstractEntity implements Blockable {
this.mLastReceivedOtrMessageId = id; this.mLastReceivedOtrMessageId = id;
} }
public int countMessages() {
synchronized (this.messages) {
return this.messages.size();
}
}
public interface OnMessageFound { public interface OnMessageFound {
public void onMessageFound(final Message message); public void onMessageFound(final Message message);
@ -419,7 +425,7 @@ public class Conversation extends AbstractEntity implements Blockable {
final SessionID sessionId = new SessionID(this.getJid().toBareJid().toString(), final SessionID sessionId = new SessionID(this.getJid().toBareJid().toString(),
presence, presence,
"xmpp"); "xmpp");
this.otrSession = new SessionImpl(sessionId, getAccount().getOtrEngine()); this.otrSession = new SessionImpl(sessionId, getAccount().getOtrService());
try { try {
if (sendStart) { if (sendStart) {
this.otrSession.startSession(); this.otrSession.startSession();
@ -491,7 +497,7 @@ public class Conversation extends AbstractEntity implements Blockable {
return null; return null;
} }
DSAPublicKey remotePubKey = (DSAPublicKey) getOtrSession().getRemotePublicKey(); DSAPublicKey remotePubKey = (DSAPublicKey) getOtrSession().getRemotePublicKey();
this.otrFingerprint = getAccount().getOtrEngine().getFingerprint(remotePubKey); this.otrFingerprint = getAccount().getOtrService().getFingerprint(remotePubKey);
} catch (final OtrCryptoException | UnsupportedOperationException ignored) { } catch (final OtrCryptoException | UnsupportedOperationException ignored) {
return null; return null;
} }

View File

@ -328,7 +328,7 @@ public class Message extends AbstractEntity {
return this.remoteMsgId == null return this.remoteMsgId == null
&& this.counterpart.equals(message.getCounterpart()) && this.counterpart.equals(message.getCounterpart())
&& this.body.equals(message.getBody()) && this.body.equals(message.getBody())
&& Math.abs(this.getTimeSent() - message.getTimeSent()) < Config.PING_TIMEOUT * 500; && Math.abs(this.getTimeSent() - message.getTimeSent()) < Config.MESSAGE_MERGE_WINDOW * 1000;
} }
} }

View File

@ -2,6 +2,7 @@ package eu.siacs.conversations.entities;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.jid.Jid;
@ -55,13 +56,16 @@ public class Roster {
} }
} }
public void clearSystemAccounts() { public List<Contact> getWithSystemAccounts() {
for (Contact contact : getContacts()) { List<Contact> with = getContacts();
contact.setPhotoUri(null); for(Iterator<Contact> iterator = with.iterator(); iterator.hasNext();) {
contact.setSystemName(null); Contact contact = iterator.next();
contact.setSystemAccount(null); if (contact.getSystemAccount() == null) {
iterator.remove();
} }
} }
return with;
}
public List<Contact> getContacts() { public List<Contact> getContacts() {
synchronized (this.contacts) { synchronized (this.contacts) {

View File

@ -11,6 +11,7 @@ import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
public abstract class AbstractParser { public abstract class AbstractParser {
@ -20,23 +21,24 @@ public abstract class AbstractParser {
this.mXmppConnectionService = service; this.mXmppConnectionService = service;
} }
protected long getTimestamp(Element packet) { public static Long getTimestamp(Element element, Long defaultValue) {
long now = System.currentTimeMillis(); Element delay = element.findChild("delay","urn:xmpp:delay");
Element delay = packet.findChild("delay"); if (delay != null) {
if (delay == null) {
return now;
}
String stamp = delay.getAttribute("stamp"); String stamp = delay.getAttribute("stamp");
if (stamp == null) { if (stamp != null) {
return now;
}
try { try {
long time = parseTimestamp(stamp).getTime(); return AbstractParser.parseTimestamp(delay.getAttribute("stamp")).getTime();
return now < time ? now : time;
} catch (ParseException e) { } catch (ParseException e) {
return now; return defaultValue;
} }
} }
}
return defaultValue;
}
protected long getTimestamp(Element packet) {
return getTimestamp(packet,System.currentTimeMillis());
}
public static Date parseTimestamp(String timestamp) throws ParseException { public static Date parseTimestamp(String timestamp) throws ParseException {
timestamp = timestamp.replace("Z", "+0000"); timestamp = timestamp.replace("Z", "+0000");
@ -46,14 +48,11 @@ public abstract class AbstractParser {
return dateFormat.parse(timestamp); return dateFormat.parse(timestamp);
} }
protected void updateLastseen(final Element packet, final Account account, protected void updateLastseen(final Element packet, final Account account, final boolean presenceOverwrite) {
final boolean presenceOverwrite) { updateLastseen(packet, account, packet.getAttributeAsJid("from"), presenceOverwrite);
final Jid from = packet.getAttributeAsJid("from");
updateLastseen(packet, account, from, presenceOverwrite);
} }
protected void updateLastseen(final Element packet, final Account account, final Jid from, protected void updateLastseen(final Element packet, final Account account, final Jid from, final boolean presenceOverwrite) {
final boolean presenceOverwrite) {
final String presence = from == null || from.isBareJid() ? "" : from.getResourcepart(); final String presence = from == null || from.isBareJid() ? "" : from.getResourcepart();
final Contact contact = account.getRoster().getContact(from); final Contact contact = account.getRoster().getContact(from);
final long timestamp = getTimestamp(packet); final long timestamp = getTimestamp(packet);
@ -70,10 +69,6 @@ public abstract class AbstractParser {
if (item == null) { if (item == null) {
return null; return null;
} }
Element data = item.findChild("data", "urn:xmpp:avatar:data"); return item.findChildContent("data", "urn:xmpp:avatar:data");
if (data == null) {
return null;
}
return data.getContent();
} }
} }

View File

@ -1,8 +1,12 @@
package eu.siacs.conversations.parser; package eu.siacs.conversations.parser;
import android.util.Log;
import android.util.Pair;
import net.java.otr4j.session.Session; import net.java.otr4j.session.Session;
import net.java.otr4j.session.SessionStatus; import net.java.otr4j.session.SessionStatus;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
@ -25,12 +29,12 @@ public class MessageParser extends AbstractParser implements
super(service); super(service);
} }
private boolean extractChatState(Conversation conversation, final Element element) { private boolean extractChatState(Conversation conversation, final MessagePacket packet) {
ChatState state = ChatState.parse(element); ChatState state = ChatState.parse(packet);
if (state != null && conversation != null) { if (state != null && conversation != null) {
final Account account = conversation.getAccount(); final Account account = conversation.getAccount();
Jid from = element.getAttributeAsJid("from"); Jid from = packet.getFrom();
if (from != null && from.toBareJid().equals(account.getJid().toBareJid())) { if (from.toBareJid().equals(account.getJid().toBareJid())) {
conversation.setOutgoingChatState(state); conversation.setOutgoingChatState(state);
return false; return false;
} else { } else {
@ -40,86 +44,27 @@ public class MessageParser extends AbstractParser implements
return false; return false;
} }
private Message parseChat(MessagePacket packet, Account account) { private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
final Jid jid = packet.getFrom();
if (jid == null) {
return null;
}
Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid.toBareJid(), false);
String pgpBody = getPgpBody(packet);
Message finishedMessage;
if (pgpBody != null) {
finishedMessage = new Message(conversation,
pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECEIVED);
} else {
finishedMessage = new Message(conversation,
packet.getBody(), Message.ENCRYPTION_NONE,
Message.STATUS_RECEIVED);
}
finishedMessage.setRemoteMsgId(packet.getId());
finishedMessage.markable = isMarkable(packet);
if (conversation.getMode() == Conversation.MODE_MULTI
&& !jid.isBareJid()) {
final Jid trueCounterpart = conversation.getMucOptions()
.getTrueCounterpart(jid.getResourcepart());
if (trueCounterpart != null) {
updateLastseen(packet, account, trueCounterpart, false);
}
finishedMessage.setType(Message.TYPE_PRIVATE);
finishedMessage.setTrueCounterpart(trueCounterpart);
if (conversation.hasDuplicateMessage(finishedMessage)) {
return null;
}
} else {
updateLastseen(packet, account, true);
}
finishedMessage.setCounterpart(jid);
finishedMessage.setTime(getTimestamp(packet));
extractChatState(conversation,packet);
return finishedMessage;
}
private Message parseOtrChat(MessagePacket packet, Account account) {
final Jid to = packet.getTo();
final Jid from = packet.getFrom();
if (to == null || from == null) {
return null;
}
boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
Conversation conversation = mXmppConnectionService
.findOrCreateConversation(account, from.toBareJid(), false);
String presence; String presence;
if (from.isBareJid()) { if (from.isBareJid()) {
presence = ""; presence = "";
} else { } else {
presence = from.getResourcepart(); presence = from.getResourcepart();
} }
extractChatState(conversation, packet);
updateLastseen(packet, account, true);
String body = packet.getBody();
if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) { if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
conversation.endOtrIfNeeded(); conversation.endOtrIfNeeded();
} }
if (!conversation.hasValidOtrSession()) { if (!conversation.hasValidOtrSession()) {
if (properlyAddressed) {
conversation.startOtrSession(presence,false); conversation.startOtrSession(presence,false);
} else { } else {
return null; String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
}
} else {
String foreignPresence = conversation.getOtrSession()
.getSessionID().getUserID();
if (!foreignPresence.equals(presence)) { if (!foreignPresence.equals(presence)) {
conversation.endOtrIfNeeded(); conversation.endOtrIfNeeded();
if (properlyAddressed) {
conversation.startOtrSession(presence, false); conversation.startOtrSession(presence, false);
} else {
return null;
}
} }
} }
try { try {
conversation.setLastReceivedOtrMessageId(packet.getId()); conversation.setLastReceivedOtrMessageId(id);
Session otrSession = conversation.getOtrSession(); Session otrSession = conversation.getOtrSession();
SessionStatus before = otrSession.getSessionStatus(); SessionStatus before = otrSession.getSessionStatus();
body = otrSession.transformReceiving(body); body = otrSession.transformReceiving(body);
@ -140,12 +85,7 @@ public class MessageParser extends AbstractParser implements
conversation.setSymmetricKey(CryptoHelper.hexToBytes(key)); conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
return null; return null;
} }
Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
Message.STATUS_RECEIVED);
finishedMessage.setTime(getTimestamp(packet));
finishedMessage.setRemoteMsgId(packet.getId());
finishedMessage.markable = isMarkable(packet);
finishedMessage.setCounterpart(from);
conversation.setLastReceivedOtrMessageId(null); conversation.setLastReceivedOtrMessageId(null);
return finishedMessage; return finishedMessage;
} catch (Exception e) { } catch (Exception e) {
@ -154,293 +94,6 @@ public class MessageParser extends AbstractParser implements
} }
} }
private Message parseGroupchat(MessagePacket packet, Account account) {
int status;
final Jid from = packet.getFrom();
if (from == null) {
return null;
}
if (mXmppConnectionService.find(account.pendingConferenceLeaves,
account, from.toBareJid()) != null) {
return null;
}
Conversation conversation = mXmppConnectionService
.findOrCreateConversation(account, from.toBareJid(), true);
final Jid trueCounterpart = conversation.getMucOptions().getTrueCounterpart(from.getResourcepart());
if (trueCounterpart != null) {
updateLastseen(packet, account, trueCounterpart, false);
}
if (packet.hasChild("subject")) {
conversation.setHasMessagesLeftOnServer(true);
conversation.getMucOptions().setSubject(packet.findChild("subject").getContent());
mXmppConnectionService.updateConversationUi();
return null;
}
final Element x = packet.findChild("x", "http://jabber.org/protocol/muc#user");
if (from.isBareJid() && (x == null || !x.hasChild("status"))) {
return null;
} else if (from.isBareJid() && x.hasChild("status")) {
for(Element child : x.getChildren()) {
if (child.getName().equals("status")) {
String code = child.getAttribute("code");
if (code.contains(MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED)) {
mXmppConnectionService.fetchConferenceConfiguration(conversation);
}
}
}
return null;
}
if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
if (mXmppConnectionService.markMessage(conversation,
packet.getId(), Message.STATUS_SEND_RECEIVED)) {
return null;
} else if (packet.getId() == null) {
Message message = conversation.findSentMessageWithBody(packet.getBody());
if (message != null) {
mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
return null;
} else {
status = Message.STATUS_SEND;
}
} else {
status = Message.STATUS_SEND;
}
} else {
status = Message.STATUS_RECEIVED;
}
String pgpBody = getPgpBody(packet);
Message finishedMessage;
if (pgpBody == null) {
finishedMessage = new Message(conversation,
packet.getBody(), Message.ENCRYPTION_NONE, status);
} else {
finishedMessage = new Message(conversation, pgpBody,
Message.ENCRYPTION_PGP, status);
}
finishedMessage.setRemoteMsgId(packet.getId());
finishedMessage.markable = isMarkable(packet);
finishedMessage.setCounterpart(from);
if (status == Message.STATUS_RECEIVED) {
finishedMessage.setTrueCounterpart(conversation.getMucOptions()
.getTrueCounterpart(from.getResourcepart()));
}
if (packet.hasChild("delay")
&& conversation.hasDuplicateMessage(finishedMessage)) {
return null;
}
finishedMessage.setTime(getTimestamp(packet));
return finishedMessage;
}
private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
int status;
final Jid fullJid;
Element forwarded;
if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
.findChild("forwarded", "urn:xmpp:forward:0");
status = Message.STATUS_RECEIVED;
} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
.findChild("forwarded", "urn:xmpp:forward:0");
status = Message.STATUS_SEND;
} else {
return null;
}
if (forwarded == null) {
return null;
}
Element message = forwarded.findChild("message");
if (message == null) {
return null;
}
if (!message.hasChild("body")) {
if (status == Message.STATUS_RECEIVED
&& message.getAttribute("from") != null) {
parseNonMessage(message, account);
} else if (status == Message.STATUS_SEND
&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
final Jid to = message.getAttributeAsJid("to");
if (to != null) {
final Conversation conversation = mXmppConnectionService.find(
mXmppConnectionService.getConversations(), account,
to.toBareJid());
if (conversation != null) {
mXmppConnectionService.markRead(conversation);
}
}
}
return null;
}
if (status == Message.STATUS_RECEIVED) {
fullJid = message.getAttributeAsJid("from");
if (fullJid == null) {
return null;
} else {
updateLastseen(message, account, true);
}
} else {
fullJid = message.getAttributeAsJid("to");
if (fullJid == null) {
return null;
}
}
if (message.hasChild("x","http://jabber.org/protocol/muc#user")
&& "chat".equals(message.getAttribute("type"))) {
return null;
}
Conversation conversation = mXmppConnectionService
.findOrCreateConversation(account, fullJid.toBareJid(), false);
String pgpBody = getPgpBody(message);
Message finishedMessage;
if (pgpBody != null) {
finishedMessage = new Message(conversation, pgpBody,
Message.ENCRYPTION_PGP, status);
} else {
String body = message.findChild("body").getContent();
finishedMessage = new Message(conversation, body,
Message.ENCRYPTION_NONE, status);
}
extractChatState(conversation,message);
finishedMessage.setTime(getTimestamp(message));
finishedMessage.setRemoteMsgId(message.getAttribute("id"));
finishedMessage.markable = isMarkable(message);
finishedMessage.setCounterpart(fullJid);
if (conversation.getMode() == Conversation.MODE_MULTI
&& !fullJid.isBareJid()) {
finishedMessage.setType(Message.TYPE_PRIVATE);
finishedMessage.setTrueCounterpart(conversation.getMucOptions()
.getTrueCounterpart(fullJid.getResourcepart()));
if (conversation.hasDuplicateMessage(finishedMessage)) {
return null;
}
}
return finishedMessage;
}
private Message parseMamMessage(MessagePacket packet, final Account account) {
final Element result = packet.findChild("result","urn:xmpp:mam:0");
if (result == null ) {
return null;
}
final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
if (query!=null) {
query.incrementTotalCount();
}
final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
if (forwarded == null) {
return null;
}
final Element message = forwarded.findChild("message");
if (message == null) {
return null;
}
final Element body = message.findChild("body");
if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
return null;
}
int encryption;
String content = getPgpBody(message);
if (content != null) {
encryption = Message.ENCRYPTION_PGP;
} else {
encryption = Message.ENCRYPTION_NONE;
content = body.getContent();
}
if (content == null) {
return null;
}
final long timestamp = getTimestamp(forwarded);
final Jid to = message.getAttributeAsJid("to");
final Jid from = message.getAttributeAsJid("from");
Jid counterpart;
int status;
Conversation conversation;
if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
status = Message.STATUS_SEND;
conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
counterpart = to;
} else if (from !=null && to != null) {
status = Message.STATUS_RECEIVED;
conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
counterpart = from;
} else {
return null;
}
Message finishedMessage = new Message(conversation,content,encryption,status);
finishedMessage.setTime(timestamp);
finishedMessage.setCounterpart(counterpart);
finishedMessage.setRemoteMsgId(message.getAttribute("id"));
finishedMessage.setServerMsgId(result.getAttribute("id"));
if (conversation.hasDuplicateMessage(finishedMessage)) {
return null;
}
if (query!=null) {
query.incrementMessageCount();
}
return finishedMessage;
}
private void parseError(final MessagePacket packet, final Account account) {
final Jid from = packet.getFrom();
mXmppConnectionService.markMessage(account, from.toBareJid(),
packet.getId(), Message.STATUS_SEND_FAILED);
}
private void parseNonMessage(Element packet, Account account) {
final Jid from = packet.getAttributeAsJid("from");
if (account.getJid().equals(from)) {
return;
}
if (extractChatState(from == null ? null : mXmppConnectionService.find(account,from), packet)) {
mXmppConnectionService.updateConversationUi();
}
Invite invite = extractInvite(packet);
if (invite != null && invite.jid != null) {
Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, invite.jid, true);
if (!conversation.getMucOptions().online()) {
conversation.getMucOptions().setPassword(invite.password);
mXmppConnectionService.databaseBackend.updateConversation(conversation);
mXmppConnectionService.joinMuc(conversation);
mXmppConnectionService.updateConversationUi();
}
}
if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
Element event = packet.findChild("event",
"http://jabber.org/protocol/pubsub#event");
parseEvent(event, from, account);
} else if (from != null && packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
String id = packet
.findChild("displayed", "urn:xmpp:chat-markers:0")
.getAttribute("id");
updateLastseen(packet, account, true);
final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), id, Message.STATUS_SEND_DISPLAYED);
Message message = displayedMessage == null ? null :displayedMessage.prev();
while (message != null
&& message.getStatus() == Message.STATUS_SEND_RECEIVED
&& message.getTimeSent() < displayedMessage.getTimeSent()) {
mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
message = message.prev();
}
} else if (from != null
&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
.getAttribute("id");
updateLastseen(packet, account, false);
mXmppConnectionService.markMessage(account, from.toBareJid(),
id, Message.STATUS_SEND_RECEIVED);
} else if (from != null
&& packet.hasChild("received", "urn:xmpp:receipts")) {
String id = packet.findChild("received", "urn:xmpp:receipts")
.getAttribute("id");
updateLastseen(packet, account, false);
mXmppConnectionService.markMessage(account, from.toBareJid(),
id, Message.STATUS_SEND_RECEIVED);
}
}
private class Invite { private class Invite {
Jid jid; Jid jid;
String password; String password;
@ -448,6 +101,20 @@ public class MessageParser extends AbstractParser implements
this.jid = jid; this.jid = jid;
this.password = password; this.password = password;
} }
public boolean execute(Account account) {
if (jid != null) {
Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true);
if (!conversation.getMucOptions().online()) {
conversation.getMucOptions().setPassword(password);
mXmppConnectionService.databaseBackend.updateConversation(conversation);
mXmppConnectionService.joinMuc(conversation);
mXmppConnectionService.updateConversationUi();
}
return true;
}
return false;
}
} }
private Invite extractInvite(Element message) { private Invite extractInvite(Element message) {
@ -469,34 +136,23 @@ public class MessageParser extends AbstractParser implements
private void parseEvent(final Element event, final Jid from, final Account account) { private void parseEvent(final Element event, final Jid from, final Account account) {
Element items = event.findChild("items"); Element items = event.findChild("items");
if (items == null) { String node = items == null ? null : items.getAttribute("node");
return; if ("urn:xmpp:avatar:metadata".equals(node)) {
}
String node = items.getAttribute("node");
if (node == null) {
return;
}
if (node.equals("urn:xmpp:avatar:metadata")) {
Avatar avatar = Avatar.parseMetadata(items); Avatar avatar = Avatar.parseMetadata(items);
if (avatar != null) { if (avatar != null) {
avatar.owner = from; avatar.owner = from;
if (mXmppConnectionService.getFileBackend().isAvatarCached( if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
avatar)) {
if (account.getJid().toBareJid().equals(from)) { if (account.getJid().toBareJid().equals(from)) {
if (account.setAvatar(avatar.getFilename())) { if (account.setAvatar(avatar.getFilename())) {
mXmppConnectionService.databaseBackend mXmppConnectionService.databaseBackend.updateAccount(account);
.updateAccount(account);
} }
mXmppConnectionService.getAvatarService().clear( mXmppConnectionService.getAvatarService().clear(account);
account);
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
mXmppConnectionService.updateAccountUi(); mXmppConnectionService.updateAccountUi();
} else { } else {
Contact contact = account.getRoster().getContact( Contact contact = account.getRoster().getContact(from);
from);
contact.setAvatar(avatar); contact.setAvatar(avatar);
mXmppConnectionService.getAvatarService().clear( mXmppConnectionService.getAvatarService().clear(contact);
contact);
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
mXmppConnectionService.updateRosterUi(); mXmppConnectionService.updateRosterUi();
} }
@ -504,15 +160,11 @@ public class MessageParser extends AbstractParser implements
mXmppConnectionService.fetchAvatar(account, avatar); mXmppConnectionService.fetchAvatar(account, avatar);
} }
} }
} else if (node.equals("http://jabber.org/protocol/nick")) { } else if ("http://jabber.org/protocol/nick".equals(node)) {
Element item = items.findChild("item"); Element i = items.findChild("item");
if (item != null) { Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
Element nick = item.findChild("nick",
"http://jabber.org/protocol/nick");
if (nick != null) { if (nick != null) {
if (from != null) { Contact contact = account.getRoster().getContact(from);
Contact contact = account.getRoster().getContact(
from);
contact.setPresenceName(nick.getContent()); contact.setPresenceName(nick.getContent());
mXmppConnectionService.getAvatarService().clear(account); mXmppConnectionService.getAvatarService().clear(account);
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
@ -520,100 +172,175 @@ public class MessageParser extends AbstractParser implements
} }
} }
} }
}
}
private String getPgpBody(Element message) { private boolean handleErrorMessage(Account account, MessagePacket packet) {
Element child = message.findChild("x", "jabber:x:encrypted"); if (packet.getType() == MessagePacket.TYPE_ERROR) {
if (child == null) { Jid from = packet.getFrom();
return null; if (from != null) {
} else { mXmppConnectionService.markMessage(account, from.toBareJid(), packet.getId(), Message.STATUS_SEND_FAILED);
return child.getContent();
} }
return true;
} }
return false;
private boolean isMarkable(Element message) {
return message.hasChild("markable", "urn:xmpp:chat-markers:0");
} }
@Override @Override
public void onMessagePacketReceived(Account account, MessagePacket packet) { public void onMessagePacketReceived(Account account, MessagePacket original) {
Message message = null; if (handleErrorMessage(account, original)) {
this.parseNick(packet, account); return;
if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
if ((packet.getBody() != null)
&& (packet.getBody().startsWith("?OTR"))) {
message = this.parseOtrChat(packet, account);
if (message != null) {
message.markUnread();
} }
} else if (packet.hasChild("body") && extractInvite(packet) == null) { final MessagePacket packet;
message = this.parseChat(packet, account); Long timestamp = null;
if (message != null) { final boolean isForwarded;
message.markUnread(); String serverMsgId = null;
final Element fin = original.findChild("fin", "urn:xmpp:mam:0");
if (fin != null) {
mXmppConnectionService.getMessageArchiveService().processFin(fin,original.getFrom());
return;
} }
} else if (packet.hasChild("received", "urn:xmpp:carbons:2") final Element result = original.findChild("result","urn:xmpp:mam:0");
|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) { final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
message = this.parseCarbonMessage(packet, account); if (query != null && query.validFrom(original.getFrom())) {
if (message != null) { Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", "urn:xmpp:mam:0");
if (message.getStatus() == Message.STATUS_SEND) { if (f == null) {
account.activateGracePeriod(); return;
mXmppConnectionService.markRead(message.getConversation()); }
timestamp = f.second;
packet = f.first;
isForwarded = true;
serverMsgId = result.getAttribute("id");
query.incrementTotalCount();
} else if (query != null) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
return;
} else if (original.fromServer(account)) {
Pair<MessagePacket, Long> f;
f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
packet = f != null ? f.first : original;
if (handleErrorMessage(account, packet)) {
return;
}
timestamp = f != null ? f.second : null;
isForwarded = f != null;
} else { } else {
message.markUnread(); packet = original;
isForwarded = false;
} }
if (timestamp == null) {
timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
} }
} else if (packet.hasChild("result","urn:xmpp:mam:0")) { final String body = packet.getBody();
message = parseMamMessage(packet, account); final String encrypted = packet.findChildContent("x", "jabber:x:encrypted");
int status;
final Jid counterpart;
final Jid to = packet.getTo();
final Jid from = packet.getFrom();
final String remoteMsgId = packet.getId();
boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
if (packet.fromAccount(account)) {
status = Message.STATUS_SEND;
counterpart = to;
} else {
status = Message.STATUS_RECEIVED;
counterpart = from;
}
if (from == null || to == null) {
Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
return;
}
Invite invite = extractInvite(packet);
if (invite != null && invite.execute(account)) {
return;
}
if (extractChatState(mXmppConnectionService.find(account,from), packet)) {
mXmppConnectionService.updateConversationUi();
}
if (body != null || encrypted != null) {
Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
if (isTypeGroupChat) {
if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
status = Message.STATUS_SEND_RECEIVED;
if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
return;
} else {
Message message = conversation.findSentMessageWithBody(body);
if (message != null) { if (message != null) {
Conversation conversation = message.getConversation(); message.setRemoteMsgId(remoteMsgId);
mXmppConnectionService.markMessage(message, status);
return;
}
}
} else {
status = Message.STATUS_RECEIVED;
}
}
Message message;
if (body != null && body.startsWith("?OTR")) {
if (!isForwarded && !isTypeGroupChat && properlyAddressed) {
message = parseOtrChat(body, from, remoteMsgId, conversation);
if (message == null) {
return;
}
} else {
message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
}
} else if (encrypted != null) {
message = new Message(conversation, encrypted, Message.ENCRYPTION_PGP, status);
} else {
message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
}
message.setCounterpart(counterpart);
message.setRemoteMsgId(remoteMsgId);
message.setServerMsgId(serverMsgId);
message.setTime(timestamp);
message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
if (conversation.getMode() == Conversation.MODE_MULTI) {
message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
if (!isTypeGroupChat) {
message.setType(Message.TYPE_PRIVATE);
}
}
updateLastseen(packet,account,true);
boolean checkForDuplicates = serverMsgId != null
|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
|| message.getType() == Message.TYPE_PRIVATE;
if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
return;
}
if (query != null) {
query.incrementMessageCount();
}
conversation.add(message); conversation.add(message);
mXmppConnectionService.databaseBackend.createMessage(message); if (serverMsgId == null) {
} if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
return; mXmppConnectionService.markRead(conversation);
} else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
Element fin = packet.findChild("fin","urn:xmpp:mam:0");
mXmppConnectionService.getMessageArchiveService().processFin(fin);
} else {
parseNonMessage(packet, account);
}
} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
message = this.parseGroupchat(packet, account);
if (message != null) {
if (message.getStatus() == Message.STATUS_RECEIVED) {
message.markUnread();
} else {
mXmppConnectionService.markRead(message.getConversation());
account.activateGracePeriod(); account.activateGracePeriod();
} else {
message.markUnread();
} }
mXmppConnectionService.updateConversationUi();
} }
} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
this.parseError(packet, account); if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded) {
return;
} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
this.parseHeadline(packet, account);
return;
}
if ((message == null) || (message.getBody() == null)) {
return;
}
if ((mXmppConnectionService.confirmMessages())
&& ((packet.getId() != null))) {
if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) { if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
MessagePacket receipt = mXmppConnectionService MessagePacket receipt = mXmppConnectionService
.getMessageGenerator().received(account, packet, .getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
"urn:xmpp:chat-markers:0");
mXmppConnectionService.sendMessagePacket(account, receipt); mXmppConnectionService.sendMessagePacket(account, receipt);
} }
if (packet.hasChild("request", "urn:xmpp:receipts")) { if (packet.hasChild("request", "urn:xmpp:receipts")) {
MessagePacket receipt = mXmppConnectionService MessagePacket receipt = mXmppConnectionService
.getMessageGenerator().received(account, packet, .getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
"urn:xmpp:receipts");
mXmppConnectionService.sendMessagePacket(account, receipt); mXmppConnectionService.sendMessagePacket(account, receipt);
} }
} }
Conversation conversation = message.getConversation();
conversation.add(message);
if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) { if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) { if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
mXmppConnectionService.updateConversation(conversation); mXmppConnectionService.updateConversation(conversation);
@ -627,38 +354,63 @@ public class MessageParser extends AbstractParser implements
conversation.endOtrIfNeeded(); conversation.endOtrIfNeeded();
} }
if (packet.getType() != MessagePacket.TYPE_ERROR) { if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
if (message.getEncryption() == Message.ENCRYPTION_NONE
|| mXmppConnectionService.saveEncryptedMessages()) {
mXmppConnectionService.databaseBackend.createMessage(message); mXmppConnectionService.databaseBackend.createMessage(message);
} }
}
final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager(); final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) { if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
manager.createNewConnection(message); manager.createNewConnection(message);
} else if (!message.isRead()) { } else if (!message.isRead()) {
mXmppConnectionService.getNotificationService().push(message); mXmppConnectionService.getNotificationService().push(message);
} }
} else { //no body
if (packet.hasChild("subject") && isTypeGroupChat) {
Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
return;
} }
private void parseHeadline(MessagePacket packet, Account account) {
if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
Element event = packet.findChild("event",
"http://jabber.org/protocol/pubsub#event");
parseEvent(event, packet.getFrom(), account);
} }
} }
private void parseNick(MessagePacket packet, Account account) { Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
Element nick = packet.findChild("nick", if (received == null) {
"http://jabber.org/protocol/nick"); received = packet.findChild("received", "urn:xmpp:receipts");
}
if (received != null && !packet.fromAccount(account)) {
mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
}
Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
if (displayed != null) {
if (packet.fromAccount(account)) {
Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
if (conversation != null) {
mXmppConnectionService.markRead(conversation);
}
} else {
updateLastseen(packet, account, true);
final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
Message message = displayedMessage == null ? null : displayedMessage.prev();
while (message != null
&& message.getStatus() == Message.STATUS_SEND_RECEIVED
&& message.getTimeSent() < displayedMessage.getTimeSent()) {
mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
message = message.prev();
}
}
}
Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
if (event != null) {
parseEvent(event, from, account);
}
String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
if (nick != null) { if (nick != null) {
if (packet.getFrom() != null) { Contact contact = account.getRoster().getContact(from);
Contact contact = account.getRoster().getContact( contact.setPresenceName(nick);
packet.getFrom());
contact.setPresenceName(nick.getContent());
}
} }
} }
} }

View File

@ -45,65 +45,17 @@ public class PresenceParser extends AbstractParser implements
} }
public void parseContactPresence(PresencePacket packet, Account account) { public void parseContactPresence(PresencePacket packet, Account account) {
PresenceGenerator mPresenceGenerator = mXmppConnectionService PresenceGenerator mPresenceGenerator = mXmppConnectionService.getPresenceGenerator();
.getPresenceGenerator(); final Jid from = packet.getFrom();
if (packet.getFrom() == null) { if (from == null) {
return; return;
} }
final Jid from = packet.getFrom(); final String type = packet.getAttribute("type");
String type = packet.getAttribute("type"); final Contact contact = account.getRoster().getContact(from);
Contact contact = account.getRoster().getContact(packet.getFrom());
if (type == null) { if (type == null) {
String presence; String presence = from.isBareJid() ? "" : from.getResourcepart();
if (!from.isBareJid()) { contact.setPresenceName(packet.findChildContent("nick", "http://jabber.org/protocol/nick"));
presence = from.getResourcepart(); Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
} else {
presence = "";
}
int sizeBefore = contact.getPresences().size();
contact.updatePresence(presence,
Presences.parseShow(packet.findChild("show")));
PgpEngine pgp = mXmppConnectionService.getPgpEngine();
if (pgp != null) {
Element x = packet.findChild("x", "jabber:x:signed");
if (x != null) {
Element status = packet.findChild("status");
String msg;
if (status != null) {
msg = status.getContent();
} else {
msg = "";
}
contact.setPgpKeyId(pgp.fetchKeyId(account, msg,
x.getContent()));
}
}
boolean online = sizeBefore < contact.getPresences().size();
updateLastseen(packet, account, false);
mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, online);
} else if (type.equals("unavailable")) {
if (from.isBareJid()) {
contact.clearPresences();
} else {
contact.removePresence(from.getResourcepart());
}
mXmppConnectionService.onContactStatusChanged
.onContactStatusChanged(contact, false);
} else if (type.equals("subscribe")) {
if (contact.getOption(Contact.Options.PREEMPTIVE_GRANT)) {
mXmppConnectionService.sendPresencePacket(account,
mPresenceGenerator.sendPresenceUpdatesTo(contact));
} else {
contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
}
}
Element nick = packet.findChild("nick",
"http://jabber.org/protocol/nick");
if (nick != null) {
contact.setPresenceName(nick.getContent());
}
Element x = packet.findChild("x","vcard-temp:x:update");
Avatar avatar = Avatar.parsePresence(x);
if (avatar != null && !contact.isSelf()) { if (avatar != null && !contact.isSelf()) {
avatar.owner = from.toBareJid(); avatar.owner = from.toBareJid();
if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) { if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
@ -116,6 +68,33 @@ public class PresenceParser extends AbstractParser implements
mXmppConnectionService.fetchAvatar(account, avatar); mXmppConnectionService.fetchAvatar(account, avatar);
} }
} }
int sizeBefore = contact.getPresences().size();
contact.updatePresence(presence, Presences.parseShow(packet.findChild("show")));
PgpEngine pgp = mXmppConnectionService.getPgpEngine();
Element x = packet.findChild("x", "jabber:x:signed");
if (pgp != null && x != null) {
Element status = packet.findChild("status");
String msg = status != null ? status.getContent() : "";
contact.setPgpKeyId(pgp.fetchKeyId(account, msg, x.getContent()));
}
boolean online = sizeBefore < contact.getPresences().size();
updateLastseen(packet, account, false);
mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, online);
} else if (type.equals("unavailable")) {
if (from.isBareJid()) {
contact.clearPresences();
} else {
contact.removePresence(from.getResourcepart());
}
mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, false);
} else if (type.equals("subscribe")) {
if (contact.getOption(Contact.Options.PREEMPTIVE_GRANT)) {
mXmppConnectionService.sendPresencePacket(account,
mPresenceGenerator.sendPresenceUpdatesTo(contact));
} else {
contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
}
}
mXmppConnectionService.updateRosterUi(); mXmppConnectionService.updateRosterUi();
} }

View File

@ -166,12 +166,12 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
public void processFin(Element fin) { public void processFin(Element fin, Jid from) {
if (fin == null) { if (fin == null) {
return; return;
} }
Query query = findQuery(fin.getAttribute("queryid")); Query query = findQuery(fin.getAttribute("queryid"));
if (query == null) { if (query == null || !query.validFrom(from)) {
return; return;
} }
boolean complete = fin.getAttributeAsBoolean("complete"); boolean complete = fin.getAttributeAsBoolean("complete");
@ -336,6 +336,14 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
return this.messageCount; return this.messageCount;
} }
public boolean validFrom(Jid from) {
if (muc()) {
return getWith().equals(from);
} else {
return (from == null) || account.getJid().toBareJid().equals(from.toBareJid());
}
}
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();

View File

@ -134,6 +134,7 @@ public class NotificationService {
} }
public void push(final Message message) { public void push(final Message message) {
mXmppConnectionService.updateUnreadCountBadge();
if (!notify(message)) { if (!notify(message)) {
return; return;
} }

View File

@ -77,6 +77,7 @@ import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener; import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
import eu.siacs.conversations.utils.PRNGFixes; import eu.siacs.conversations.utils.PRNGFixes;
import eu.siacs.conversations.utils.PhoneHelper; import eu.siacs.conversations.utils.PhoneHelper;
import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
import eu.siacs.conversations.utils.Xmlns; import eu.siacs.conversations.utils.Xmlns;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnBindListener; import eu.siacs.conversations.xmpp.OnBindListener;
@ -100,6 +101,7 @@ import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket; import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
import me.leolin.shortcutbadger.ShortcutBadger;
public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener { public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
@ -118,6 +120,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
startService(intent); startService(intent);
} }
}; };
private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
private final IBinder mBinder = new XmppConnectionBinder(); private final IBinder mBinder = new XmppConnectionBinder();
private final List<Conversation> conversations = new CopyOnWriteArrayList<>(); private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
private final FileObserver fileObserver = new FileObserver( private final FileObserver fileObserver = new FileObserver(
@ -203,6 +209,18 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
private OnMessagePacketReceived mMessageParser = new MessageParser(this); private OnMessagePacketReceived mMessageParser = new MessageParser(this);
private OnPresencePacketReceived mPresenceParser = new PresenceParser(this); private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
private IqParser mIqParser = new IqParser(this); private IqParser mIqParser = new IqParser(this);
private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.ERROR) {
Element error = packet.findChild("error");
String text = error != null ? error.findChildContent("text") : null;
if (text != null) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
}
}
}
};
private MessageGenerator mMessageGenerator = new MessageGenerator(this); private MessageGenerator mMessageGenerator = new MessageGenerator(this);
private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this); private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
private List<Account> accounts; private List<Account> accounts;
@ -214,7 +232,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
private final List<String> mInProgressAvatarFetches = new ArrayList<>(); private final List<String> mInProgressAvatarFetches = new ArrayList<>();
private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this); private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
private OnConversationUpdate mOnConversationUpdate = null; private OnConversationUpdate mOnConversationUpdate = null;
private Integer convChangedListenerCount = 0; private int convChangedListenerCount = 0;
private int unreadCount = 0;
private OnAccountUpdate mOnAccountUpdate = null; private OnAccountUpdate mOnAccountUpdate = null;
private OnStatusChanged statusListener = new OnStatusChanged() { private OnStatusChanged statusListener = new OnStatusChanged() {
@ -359,7 +378,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
callback.success(message); callback.success(message);
} }
} else { } else {
new Thread(new Runnable() { mFileAddingExecutor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@ -374,8 +393,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
callback.error(e.getResId(),message); callback.error(e.getResId(),message);
} }
} }
}).start(); });
} }
} }
@ -391,7 +409,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} }
message.setCounterpart(conversation.getNextCounterpart()); message.setCounterpart(conversation.getNextCounterpart());
message.setType(Message.TYPE_IMAGE); message.setType(Message.TYPE_IMAGE);
new Thread(new Runnable() { mFileAddingExecutor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -406,7 +424,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
callback.error(e.getResId(), message); callback.error(e.getResId(), message);
} }
} }
}).start(); });
} }
public Conversation find(Bookmark bookmark) { public Conversation find(Bookmark bookmark) {
@ -485,8 +503,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime(); long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
if (lastSent > lastReceived) { if (lastSent > lastReceived) {
if (pingTimeoutIn < 0) { if (pingTimeoutIn < 0) {
long age = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000; Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout. connection age was: "+age+"s");
this.reconnectAccount(account, true); this.reconnectAccount(account, true);
} else { } else {
int secs = (int) (pingTimeoutIn / 1000); int secs = (int) (pingTimeoutIn / 1000);
@ -573,7 +590,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
this.accounts = databaseBackend.getAccounts(); this.accounts = databaseBackend.getAccounts();
for (final Account account : this.accounts) { for (final Account account : this.accounts) {
account.initOtrEngine(this); account.initAccountServices(this);
} }
restoreFromDatabase(); restoreFromDatabase();
@ -902,7 +919,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
for (Bookmark bookmark : account.getBookmarks()) { for (Bookmark bookmark : account.getBookmarks()) {
storage.addChild(bookmark); storage.addChild(bookmark);
} }
sendIqPacket(account, iqPacket, null); sendIqPacket(account, iqPacket, mDefaultIqHandler);
} }
public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) { public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
@ -914,7 +931,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void run() { public void run() {
Log.d(Config.LOGTAG,"start merging phone contacts with roster"); Log.d(Config.LOGTAG,"start merging phone contacts with roster");
for (Account account : accounts) { for (Account account : accounts) {
account.getRoster().clearSystemAccounts(); List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
for (Bundle phoneContact : phoneContacts) { for (Bundle phoneContact : phoneContacts) {
if (Thread.interrupted()) { if (Thread.interrupted()) {
Log.d(Config.LOGTAG,"interrupted merging phone contacts"); Log.d(Config.LOGTAG,"interrupted merging phone contacts");
@ -931,9 +948,18 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
+ "#" + "#"
+ phoneContact.getString("lookup"); + phoneContact.getString("lookup");
contact.setSystemAccount(systemAccount); contact.setSystemAccount(systemAccount);
contact.setPhotoUri(phoneContact.getString("photouri")); if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
getAvatarService().clear(contact); getAvatarService().clear(contact);
}
contact.setSystemName(phoneContact.getString("displayname")); contact.setSystemName(phoneContact.getString("displayname"));
withSystemAccounts.remove(contact);
}
for(Contact contact : withSystemAccounts) {
contact.setSystemAccount(null);
contact.setSystemName(null);
if (contact.setPhotoUri(null)) {
getAvatarService().clear(contact);
}
} }
} }
Log.d(Config.LOGTAG,"finished merging phone contacts"); Log.d(Config.LOGTAG,"finished merging phone contacts");
@ -954,7 +980,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Account account = accountLookupTable.get(conversation.getAccountUuid()); Account account = accountLookupTable.get(conversation.getAccountUuid());
conversation.setAccount(account); conversation.setAccount(account);
} }
new Thread(new Runnable() { Runnable runnable =new Runnable() {
@Override @Override
public void run() { public void run() {
Log.d(Config.LOGTAG,"restoring roster"); Log.d(Config.LOGTAG,"restoring roster");
@ -975,7 +1001,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Log.d(Config.LOGTAG,"restored all messages"); Log.d(Config.LOGTAG,"restored all messages");
updateConversationUi(); updateConversationUi();
} }
}).start(); };
mDatabaseExecutor.execute(runnable);
} }
} }
@ -1044,7 +1071,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) { if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
return; return;
} }
new Thread(new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
final Account account = conversation.getAccount(); final Account account = conversation.getAccount();
@ -1063,7 +1090,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
callback.informUser(R.string.fetching_history_from_server); callback.informUser(R.string.fetching_history_from_server);
} }
} }
}).start(); };
mDatabaseExecutor.execute(runnable);
} }
public List<Account> getAccounts() { public List<Account> getAccounts() {
@ -1175,7 +1203,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} }
public void createAccount(final Account account) { public void createAccount(final Account account) {
account.initOtrEngine(this); account.initAccountServices(this);
databaseBackend.createAccount(account); databaseBackend.createAccount(account);
this.accounts.add(account); this.accounts.add(account);
this.reconnectAccountInBackground(account); this.reconnectAccountInBackground(account);
@ -1690,7 +1718,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} }
} }
IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString()); IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
sendIqPacket(conference.getAccount(), request, null); sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
} }
public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) { public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
@ -1834,7 +1862,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT); && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET); final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
iq.query(Xmlns.ROSTER).addChild(contact.asElement()); iq.query(Xmlns.ROSTER).addChild(contact.asElement());
account.getXmppConnection().sendIqPacket(iq, null); account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
if (sendUpdates) { if (sendUpdates) {
sendPresencePacket(account, sendPresencePacket(account,
mPresenceGenerator.sendPresenceUpdatesTo(contact)); mPresenceGenerator.sendPresenceUpdatesTo(contact));
@ -2001,8 +2029,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Element vCard = packet.findChild("vCard", "vcard-temp"); Element vCard = packet.findChild("vCard", "vcard-temp");
Element photo = vCard != null ? vCard.findChild("PHOTO") : null; Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
Element binval = photo != null ? photo.findChild("BINVAL") : null; String image = photo != null ? photo.findChildContent("BINVAL") : null;
String image = binval != null ? binval.getContent() : null;
if (image != null) { if (image != null) {
avatar.image = image; avatar.image = image;
if (getFileBackend().save(avatar)) { if (getFileBackend().save(avatar)) {
@ -2065,7 +2092,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Element item = iq.query(Xmlns.ROSTER).addChild("item"); Element item = iq.query(Xmlns.ROSTER).addChild("item");
item.setAttribute("jid", contact.getJid().toString()); item.setAttribute("jid", contact.getJid().toString());
item.setAttribute("subscription", "remove"); item.setAttribute("subscription", "remove");
account.getXmppConnection().sendIqPacket(iq, null); account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
} }
} }
@ -2262,6 +2289,20 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void markRead(final Conversation conversation) { public void markRead(final Conversation conversation) {
mNotificationService.clear(conversation); mNotificationService.clear(conversation);
conversation.markRead(); conversation.markRead();
updateUnreadCountBadge();
}
public synchronized void updateUnreadCountBadge() {
int count = unreadCount();
if (unreadCount != count) {
Log.d(Config.LOGTAG, "update unread count to " + count);
if (count > 0) {
ShortcutBadger.with(getApplicationContext()).count(count);
} else {
ShortcutBadger.with(getApplicationContext()).remove();
}
unreadCount = count;
}
} }
public void sendReadMarker(final Conversation conversation) { public void sendReadMarker(final Conversation conversation) {
@ -2309,13 +2350,14 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} }
public void syncRosterToDisk(final Account account) { public void syncRosterToDisk(final Account account) {
new Thread(new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
databaseBackend.writeRoster(account.getRoster()); databaseBackend.writeRoster(account.getRoster());
} }
}).start(); };
mDatabaseExecutor.execute(runnable);
} }

View File

@ -10,6 +10,7 @@ import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.Intents;
@ -126,6 +127,7 @@ public class ContactDetailsActivity extends XmppActivity implements OnAccountUpd
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (contact.getSystemAccount() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder( AlertDialog.Builder builder = new AlertDialog.Builder(
ContactDetailsActivity.this); ContactDetailsActivity.this);
builder.setTitle(getString(R.string.action_add_phone_book)); builder.setTitle(getString(R.string.action_add_phone_book));
@ -134,6 +136,14 @@ public class ContactDetailsActivity extends XmppActivity implements OnAccountUpd
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
builder.setPositiveButton(getString(R.string.add), addToPhonebook); builder.setPositiveButton(getString(R.string.add), addToPhonebook);
builder.create().show(); builder.create().show();
} else {
String[] systemAccount = contact.getSystemAccount().split("#");
long id = Long.parseLong(systemAccount[0]);
Uri uri = ContactsContract.Contacts.getLookupUri(id, systemAccount[1]);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} }
}; };
@ -340,12 +350,9 @@ public class ContactDetailsActivity extends XmppActivity implements OnAccountUpd
} else { } else {
contactJidTv.setText(contact.getJid().toString()); contactJidTv.setText(contact.getJid().toString());
} }
accountJidTv.setText(getString(R.string.using_account, contact accountJidTv.setText(getString(R.string.using_account, contact.getAccount().getJid().toBareJid()));
.getAccount().getJid().toBareJid())); badge.setImageBitmap(avatarService().get(contact, getPixel(72)));
prepareContactBadge(badge, contact); badge.setOnClickListener(this.onBadgeClick);
if (contact.getSystemAccount() == null) {
badge.setOnClickListener(onBadgeClick);
}
keys.removeAllViews(); keys.removeAllViews();
boolean hasKeys = false; boolean hasKeys = false;
@ -419,15 +426,6 @@ public class ContactDetailsActivity extends XmppActivity implements OnAccountUpd
} }
} }
private void prepareContactBadge(QuickContactBadge badge, Contact contact) {
if (contact.getSystemAccount() != null) {
String[] systemAccount = contact.getSystemAccount().split("#");
long id = Long.parseLong(systemAccount[0]);
badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
}
badge.setImageBitmap(avatarService().get(contact, getPixel(72)));
}
protected void confirmToDeleteFingerprint(final String fingerprint) { protected void confirmToDeleteFingerprint(final String fingerprint) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.delete_fingerprint); builder.setTitle(R.string.delete_fingerprint);

View File

@ -479,6 +479,9 @@ public class ConversationActivity extends XmppActivity
case ATTACHMENT_CHOICE_TAKE_PHOTO: case ATTACHMENT_CHOICE_TAKE_PHOTO:
getPreferences().edit().putString("recently_used_quick_action","photo").apply(); getPreferences().edit().putString("recently_used_quick_action","photo").apply();
break; break;
case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
getPreferences().edit().putString("recently_used_quick_action","picture").apply();
break;
} }
final Conversation conversation = getSelectedConversation(); final Conversation conversation = getSelectedConversation();
final int encryption = conversation.getNextEncryption(forceEncryption()); final int encryption = conversation.getNextEncryption(forceEncryption());

View File

@ -256,6 +256,9 @@ public class ConversationFragment extends Fragment implements EditMessage.Keyboa
case RECORD_VOICE: case RECORD_VOICE:
activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE); activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
break; break;
case CHOOSE_PICTURE:
activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
break;
case CANCEL: case CANCEL:
if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) { if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
conversation.setNextCounterpart(null); conversation.setNextCounterpart(null);
@ -818,7 +821,7 @@ public class ConversationFragment extends Fragment implements EditMessage.Keyboa
updateChatMsgHint(); updateChatMsgHint();
} }
enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL} enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
private int getSendButtonImageResource(SendButtonAction action, int status) { private int getSendButtonImageResource(SendButtonAction action, int status) {
switch (action) { switch (action) {
@ -887,6 +890,19 @@ public class ConversationFragment extends Fragment implements EditMessage.Keyboa
default: default:
return R.drawable.ic_send_cancel_offline; return R.drawable.ic_send_cancel_offline;
} }
case CHOOSE_PICTURE:
switch (status) {
case Presences.CHAT:
case Presences.ONLINE:
return R.drawable.ic_send_picture_online;
case Presences.AWAY:
return R.drawable.ic_send_picture_away;
case Presences.XA:
case Presences.DND:
return R.drawable.ic_send_picture_dnd;
default:
return R.drawable.ic_send_picture_offline;
}
} }
return R.drawable.ic_send_text_offline; return R.drawable.ic_send_text_offline;
} }
@ -920,6 +936,9 @@ public class ConversationFragment extends Fragment implements EditMessage.Keyboa
case "voice": case "voice":
action = SendButtonAction.RECORD_VOICE; action = SendButtonAction.RECORD_VOICE;
break; break;
case "picture":
action = SendButtonAction.CHOOSE_PICTURE;
break;
default: default:
action = SendButtonAction.TEXT; action = SendButtonAction.TEXT;
break; break;

View File

@ -20,11 +20,19 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Random; import java.util.Random;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.regex.Pattern;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
public class DNSHelper { public class DNSHelper {
public static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
public static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
public static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
public static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
public static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
protected static Client client = new Client(); protected static Client client = new Client();
public static Bundle getSRVRecord(final Jid jid) throws IOException { public static Bundle getSRVRecord(final Jid jid) throws IOException {
@ -37,9 +45,6 @@ public class DNSHelper {
Bundle b = queryDNS(host, ip); Bundle b = queryDNS(host, ip);
if (b.containsKey("values")) { if (b.containsKey("values")) {
return b; return b;
} else if (b.containsKey("error")
&& "nosrv".equals(b.getString("error", null))) {
return b;
} }
} }
} }
@ -50,113 +55,95 @@ public class DNSHelper {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
try { try {
String qname = "_xmpp-client._tcp." + host; String qname = "_xmpp-client._tcp." + host;
Log.d(Config.LOGTAG, Log.d(Config.LOGTAG, "using dns server: " + dnsServer.getHostAddress() + " to look up " + host);
"using dns server: " + dnsServer.getHostAddress() DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN, dnsServer.getHostAddress());
+ " to look up " + host);
DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN,
dnsServer.getHostAddress());
// How should we handle priorities and weight?
// Wikipedia has a nice article about priorities vs. weights:
// https://en.wikipedia.org/wiki/SRV_record#Provisioning_for_high_service_availability
// we bucket the SRV records based on priority, pick per priority
// a random order respecting the weight, and dump that priority by
// priority
TreeMap<Integer, ArrayList<SRV>> priorities = new TreeMap<>(); TreeMap<Integer, ArrayList<SRV>> priorities = new TreeMap<>();
TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>(); TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>();
TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>(); TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>();
for (Record[] rrset : new Record[][] { message.getAnswers(), for (Record[] rrset : new Record[][] { message.getAnswers(), message.getAdditionalResourceRecords() }) {
message.getAdditionalResourceRecords() }) {
for (Record rr : rrset) { for (Record rr : rrset) {
Data d = rr.getPayload(); Data d = rr.getPayload();
if (d instanceof SRV if (d instanceof SRV && NameUtil.idnEquals(qname, rr.getName())) {
&& NameUtil.idnEquals(qname, rr.getName())) {
SRV srv = (SRV) d; SRV srv = (SRV) d;
if (!priorities.containsKey(srv.getPriority())) { if (!priorities.containsKey(srv.getPriority())) {
priorities.put(srv.getPriority(), priorities.put(srv.getPriority(),new ArrayList<SRV>());
new ArrayList<SRV>(2));
} }
priorities.get(srv.getPriority()).add(srv); priorities.get(srv.getPriority()).add(srv);
} }
if (d instanceof A) { if (d instanceof A) {
A arecord = (A) d; A a = (A) d;
if (!ips4.containsKey(rr.getName())) { if (!ips4.containsKey(rr.getName())) {
ips4.put(rr.getName(), new ArrayList<String>(3)); ips4.put(rr.getName(), new ArrayList<String>());
} }
ips4.get(rr.getName()).add(arecord.toString()); ips4.get(rr.getName()).add(a.toString());
} }
if (d instanceof AAAA) { if (d instanceof AAAA) {
AAAA aaaa = (AAAA) d; AAAA aaaa = (AAAA) d;
if (!ips6.containsKey(rr.getName())) { if (!ips6.containsKey(rr.getName())) {
ips6.put(rr.getName(), new ArrayList<String>(3)); ips6.put(rr.getName(), new ArrayList<String>());
} }
ips6.get(rr.getName()).add("[" + aaaa.toString() + "]"); ips6.get(rr.getName()).add("[" + aaaa.toString() + "]");
} }
} }
} }
Random rnd = new Random(); ArrayList<SRV> result = new ArrayList<>();
ArrayList<SRV> result = new ArrayList<>(
priorities.size() * 2 + 1);
for (ArrayList<SRV> s : priorities.values()) { for (ArrayList<SRV> s : priorities.values()) {
// trivial case
if (s.size() <= 1) {
result.addAll(s); result.addAll(s);
continue;
}
long totalweight = 0l;
for (SRV srv : s) {
totalweight += srv.getWeight();
}
while (totalweight > 0l && s.size() > 0) {
long p = (rnd.nextLong() & 0x7fffffffffffffffl)
% totalweight;
int i = 0;
while (p > 0) {
p -= s.get(i++).getPriority();
}
if (i>0) i--;
// remove is expensive, but we have only a few entries
// anyway
SRV srv = s.remove(i);
totalweight -= srv.getWeight();
result.add(srv);
}
Collections.shuffle(s, rnd);
result.addAll(s);
} }
ArrayList<Bundle> values = new ArrayList<>();
if (result.size() == 0) { if (result.size() == 0) {
bundle.putString("error", "nosrv"); DNSMessage response;
response = client.query(host, TYPE.A, CLASS.IN, dnsServer.getHostAddress());
for(int i = 0; i < response.getAnswers().length; ++i) {
values.add(createNamePortBundle(host,5222,response.getAnswers()[i].getPayload()));
}
response = client.query(host, TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
for(int i = 0; i < response.getAnswers().length; ++i) {
values.add(createNamePortBundle(host,5222,response.getAnswers()[i].getPayload()));
}
bundle.putParcelableArrayList("values", values);
return bundle; return bundle;
} }
ArrayList<Bundle> values = new ArrayList<>();
for (SRV srv : result) { for (SRV srv : result) {
if (ips6.containsKey(srv.getName())) { if (ips6.containsKey(srv.getName())) {
values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6)); values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6));
} else {
DNSMessage response = client.query(srv.getName(), TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
for(int i = 0; i < response.getAnswers().length; ++i) {
values.add(createNamePortBundle(srv.getName(),srv.getPort(),response.getAnswers()[i].getPayload()));
}
} }
if (ips4.containsKey(srv.getName())) { if (ips4.containsKey(srv.getName())) {
values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4)); values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4));
} else {
DNSMessage response = client.query(srv.getName(), TYPE.A, CLASS.IN, dnsServer.getHostAddress());
for(int i = 0; i < response.getAnswers().length; ++i) {
values.add(createNamePortBundle(srv.getName(),srv.getPort(),response.getAnswers()[i].getPayload()));
} }
values.add(createNamePortBundle(srv.getName(),srv.getPort(),null)); }
values.add(createNamePortBundle(srv.getName(), srv.getPort()));
} }
bundle.putParcelableArrayList("values", values); bundle.putParcelableArrayList("values", values);
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
bundle.putString("error", "timeout"); bundle.putString("error", "timeout");
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG,e.getMessage());
bundle.putString("error", "unhandled"); bundle.putString("error", "unhandled");
} }
return bundle; return bundle;
} }
private static Bundle createNamePortBundle(String name, int port) {
Bundle namePort = new Bundle();
namePort.putString("name", name);
namePort.putInt("port", port);
return namePort;
}
private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) { private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) {
Bundle namePort = new Bundle(); Bundle namePort = new Bundle();
namePort.putString("name", name); namePort.putString("name", name);
@ -169,15 +156,23 @@ public class DNSHelper {
return namePort; return namePort;
} }
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); private static Bundle createNamePortBundle(String name, int port, Data data) {
Bundle namePort = new Bundle();
namePort.putString("name", name);
namePort.putInt("port", port);
if (data instanceof A) {
namePort.putString("ip", data.toString());
} else if (data instanceof AAAA) {
namePort.putString("ip","["+data.toString()+"]");
}
return namePort;
}
public static String bytesToHex(byte[] bytes) { public static boolean isIp(final String server) {
char[] hexChars = new char[bytes.length * 2]; return PATTERN_IPV4.matcher(server).matches()
for (int j = 0; j < bytes.length; j++) { || PATTERN_IPV6.matcher(server).matches()
int v = bytes[j] & 0xFF; || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
hexChars[j * 2] = hexArray[v >>> 4]; || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches();
}
return new String(hexChars);
} }
} }

View File

@ -54,8 +54,14 @@ public class GeoHelper {
Intent locationPluginIntent = new Intent("eu.siacs.conversations.location.show"); Intent locationPluginIntent = new Intent("eu.siacs.conversations.location.show");
locationPluginIntent.putExtra("latitude",latitude); locationPluginIntent.putExtra("latitude",latitude);
locationPluginIntent.putExtra("longitude",longitude); locationPluginIntent.putExtra("longitude",longitude);
if (conversation.getMode() == Conversation.MODE_SINGLE && message.getStatus() == Message.STATUS_RECEIVED) { if (conversation.getMode() == Conversation.MODE_SINGLE) {
if (message.getStatus() == Message.STATUS_RECEIVED) {
locationPluginIntent.putExtra("name",conversation.getName()); locationPluginIntent.putExtra("name",conversation.getName());
locationPluginIntent.putExtra("jid",message.getCounterpart().toString());
}
else {
locationPluginIntent.putExtra("jid",conversation.getAccount().getJid().toString());
}
} }
intents.add(locationPluginIntent); intents.add(locationPluginIntent);

View File

@ -0,0 +1,34 @@
package eu.siacs.conversations.utils;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class SerialSingleThreadExecutor implements Executor {
final Executor executor = Executors.newSingleThreadExecutor();
final Queue<Runnable> tasks = new ArrayDeque();
Runnable active;
public synchronized void execute(final Runnable r) {
tasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (active == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((active = tasks.poll()) != null) {
executor.execute(active);
}
}
}

View File

@ -57,6 +57,11 @@ public class Element {
return null; return null;
} }
public String findChildContent(String name) {
Element element = findChild(name);
return element == null ? null : element.getContent();
}
public Element findChild(String name, String xmlns) { public Element findChild(String name, String xmlns) {
for (Element child : this.children) { for (Element child : this.children) {
if (child.getName().equals(name) if (child.getName().equals(name)
@ -67,6 +72,11 @@ public class Element {
return null; return null;
} }
public String findChildContent(String name, String xmlns) {
Element element = findChild(name,xmlns);
return element == null ? null : element.getContent();
}
public boolean hasChild(final String name) { public boolean hasChild(final String name) {
return findChild(name) != null; return findChild(name) != null;
} }

View File

@ -26,6 +26,7 @@ import java.net.IDN;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -155,6 +156,14 @@ public class XmppConnection implements Runnable {
tagWriter = new TagWriter(); tagWriter = new TagWriter();
packetCallbacks.clear(); packetCallbacks.clear();
this.changeStatus(Account.State.CONNECTING); this.changeStatus(Account.State.CONNECTING);
if (DNSHelper.isIp(account.getServer().toString())) {
socket = new Socket();
try {
socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
} catch (IOException e) {
throw new UnknownHostException();
}
} else {
final Bundle result = DNSHelper.getSRVRecord(account.getServer()); final Bundle result = DNSHelper.getSRVRecord(account.getServer());
final ArrayList<Parcelable> values = result.getParcelableArrayList("values"); final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
if ("timeout".equals(result.getString("error"))) { if ("timeout".equals(result.getString("error"))) {
@ -200,12 +209,10 @@ public class XmppConnection implements Runnable {
if (socketError) { if (socketError) {
throw new UnknownHostException(); throw new UnknownHostException();
} }
} else if (result.containsKey("error")
&& "nosrv".equals(result.getString("error", null))) {
socket = new Socket(account.getServer().getDomainpart(), 5222);
} else { } else {
throw new IOException("unhandled exception in DNS resolver"); throw new IOException("unhandled exception in DNS resolver");
} }
}
final OutputStream out = socket.getOutputStream(); final OutputStream out = socket.getOutputStream();
tagWriter.setOutputStream(out); tagWriter.setOutputStream(out);
final InputStream in = socket.getInputStream(); final InputStream in = socket.getInputStream();

View File

@ -160,13 +160,18 @@ public class JingleInbandTransport extends JingleTransport {
byte[] buffer = new byte[this.bufferSize]; byte[] buffer = new byte[this.bufferSize];
try { try {
int count = fileInputStream.read(buffer); int count = fileInputStream.read(buffer);
this.remainingSize -= count; if (count == -1) {
if (count != buffer.length && count != -1) { file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest()));
this.onFileTransmissionStatusChanged.onFileTransmitted(file);
fileInputStream.close();
return;
} else if (count != buffer.length) {
int rem = fileInputStream.read(buffer,count,buffer.length-count); int rem = fileInputStream.read(buffer,count,buffer.length-count);
if (rem > 0) { if (rem > 0) {
count += rem; count += rem;
} }
} }
this.remainingSize -= count;
this.digest.update(buffer,0,count); this.digest.update(buffer,0,count);
String base64 = Base64.encodeToString(buffer,0,count, Base64.NO_WRAP); String base64 = Base64.encodeToString(buffer,0,count, Base64.NO_WRAP);
IqPacket iq = new IqPacket(IqPacket.TYPE.SET); IqPacket iq = new IqPacket(IqPacket.TYPE.SET);

View File

@ -83,8 +83,7 @@ public class Avatar {
} }
public static Avatar parsePresence(Element x) { public static Avatar parsePresence(Element x) {
Element photo = x != null ? x.findChild("photo") : null; String hash = x == null ? null : x.findChildContent("photo");
String hash = photo != null ? photo.getContent() : null;
if (hash == null) { if (hash == null) {
return null; return null;
} }

View File

@ -51,4 +51,8 @@ public class AbstractStanza extends Element {
|| getTo().equals(account.getJid().toBareJid()) || getTo().equals(account.getJid().toBareJid())
|| getTo().equals(account.getJid()); || getTo().equals(account.getJid());
} }
public boolean fromAccount(final Account account) {
return getFrom() != null && getFrom().toBareJid().equals(account.getJid().toBareJid());
}
} }

View File

@ -1,5 +1,10 @@
package eu.siacs.conversations.xmpp.stanzas; package eu.siacs.conversations.xmpp.stanzas;
import android.util.Pair;
import java.text.ParseException;
import eu.siacs.conversations.parser.AbstractParser;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
public class MessagePacket extends AbstractStanza { public class MessagePacket extends AbstractStanza {
@ -14,12 +19,7 @@ public class MessagePacket extends AbstractStanza {
} }
public String getBody() { public String getBody() {
Element body = this.findChild("body"); return findChildContent("body");
if (body != null) {
return body.getContent();
} else {
return null;
}
} }
public void setBody(String text) { public void setBody(String text) {
@ -66,4 +66,31 @@ public class MessagePacket extends AbstractStanza {
return TYPE_NORMAL; return TYPE_NORMAL;
} }
} }
public Pair<MessagePacket,Long> getForwardedMessagePacket(String name, String namespace) {
Element wrapper = findChild(name, namespace);
if (wrapper == null) {
return null;
}
Element forwarded = wrapper.findChild("forwarded", "urn:xmpp:forward:0");
if (forwarded == null) {
return null;
}
MessagePacket packet = create(forwarded.findChild("message"));
if (packet == null) {
return null;
}
Long timestamp = AbstractParser.getTimestamp(forwarded,null);
return new Pair(packet,timestamp);
}
public static MessagePacket create(Element element) {
if (element == null) {
return null;
}
MessagePacket packet = new MessagePacket();
packet.setAttributes(element.getAttributes());
packet.setChildren(element.getChildren());
return packet;
}
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 790 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 884 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 657 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 867 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 512 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 899 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1016 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 799 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@ -446,4 +446,9 @@
<item quantity="one">Изберете %d контакт</item> <item quantity="one">Изберете %d контакт</item>
<item quantity="other">Изберете %d контакта</item> <item quantity="other">Изберете %d контакта</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Замяна на бутона за изпращане с бързо действие</string>
<string name="pref_quick_action">Бързо действие</string>
<string name="none">Нищо</string>
<string name="recently_used">Използвани наскоро</string>
<string name="choose_quick_action">Изберете бързо действие</string>
</resources> </resources>

View File

@ -1,2 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View File

@ -448,4 +448,9 @@
<item quantity="few">Vybrat %d kontakty</item> <item quantity="few">Vybrat %d kontakty</item>
<item quantity="other">Vybrat %d kontaktů</item> <item quantity="other">Vybrat %d kontaktů</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Nahradit tlačítko odeslání rychlou akcí</string>
<string name="pref_quick_action">Rychlá akce</string>
<string name="none">Žádná</string>
<string name="recently_used">Naposledy použitá</string>
<string name="choose_quick_action">Vybrat rychlou akci</string>
</resources> </resources>

View File

@ -446,4 +446,9 @@
<item quantity="one">%d Kontakt ausgewählt</item> <item quantity="one">%d Kontakt ausgewählt</item>
<item quantity="other">%d Kontakte ausgewählt</item> <item quantity="other">%d Kontakte ausgewählt</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Ersetze Absende-Knopf durch Schnell-Tasten</string>
<string name="pref_quick_action">Schnell-Tasten</string>
<string name="none">keine</string>
<string name="recently_used">zuletzt verwendet</string>
<string name="choose_quick_action">wähle Schnell-Taste</string>
</resources> </resources>

View File

@ -446,4 +446,9 @@
<item quantity="one">Seleccionado %d contacto</item> <item quantity="one">Seleccionado %d contacto</item>
<item quantity="other">Seleccionados %d contactos</item> <item quantity="other">Seleccionados %d contactos</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Cambiar el botón de enviar por botón de acción rápida</string>
<string name="pref_quick_action">Acción Rápida</string>
<string name="none">Ninguna</string>
<string name="recently_used">Usada más recientemente</string>
<string name="choose_quick_action">Elegir acción rápida</string>
</resources> </resources>

View File

@ -446,4 +446,9 @@
<item quantity="one">Hautatu kontaktu %d</item> <item quantity="one">Hautatu kontaktu %d</item>
<item quantity="other">Hautatu %d kontaktu</item> <item quantity="other">Hautatu %d kontaktu</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Bidaltze botoia ekintza azkar batekin aldatu</string>
<string name="pref_quick_action">Ekintza azkarra</string>
<string name="none">Bat ere ez</string>
<string name="recently_used">Azkenengo aldiz erabilitakoa</string>
<string name="choose_quick_action">Ekintza azkarra aukeratu</string>
</resources> </resources>

View File

@ -444,4 +444,9 @@
<plurals name="select_contact"> <plurals name="select_contact">
<item quantity="other">Pilih %d kontak</item> <item quantity="other">Pilih %d kontak</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Timpa tombol kirim dengan aksi cepat</string>
<string name="pref_quick_action">Aksi Cepat</string>
<string name="none">Tak satupun</string>
<string name="recently_used">Maling sering digunakan</string>
<string name="choose_quick_action">Pilih aksi cepat</string>
</resources> </resources>

View File

@ -444,4 +444,9 @@
<plurals name="select_contact"> <plurals name="select_contact">
<item quantity="other">%d 連絡先を選択</item> <item quantity="other">%d 連絡先を選択</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">送信ボタンをクイックアクションで置き換えます</string>
<string name="pref_quick_action">クイックアクション</string>
<string name="none">なし</string>
<string name="recently_used">最近使用した</string>
<string name="choose_quick_action">クイックアクションの選択</string>
</resources> </resources>

View File

@ -444,4 +444,9 @@
<plurals name="select_contact"> <plurals name="select_contact">
<item quantity="other">%d 연락처 선택 </item> <item quantity="other">%d 연락처 선택 </item>
</plurals> </plurals>
<string name="pref_quick_action_summary">전송 버튼을 빠른 동작 버튼으로 교체</string>
<string name="pref_quick_action">빠른 동작</string>
<string name="none">없음</string>
<string name="recently_used">최근 사용된 항목</string>
<string name="choose_quick_action">빠른 동작 선택</string>
</resources> </resources>

View File

@ -446,4 +446,9 @@
<item quantity="one">Selecteer %d contact</item> <item quantity="one">Selecteer %d contact</item>
<item quantity="other">Selecteer %d contacten</item> <item quantity="other">Selecteer %d contacten</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Vervang verzendknop door snelle actie</string>
<string name="pref_quick_action">Snelle actie</string>
<string name="none">Geen</string>
<string name="recently_used">Recent gebruikt</string>
<string name="choose_quick_action">Kies snelle actie</string>
</resources> </resources>

View File

@ -448,4 +448,9 @@
<item quantity="few">%d kontakty wybrane</item> <item quantity="few">%d kontakty wybrane</item>
<item quantity="other">%d kontaktów wybranych</item> <item quantity="other">%d kontaktów wybranych</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Zastąp przycisk wysyłania szybką akcją</string>
<string name="pref_quick_action">Szybka akcja</string>
<string name="none">Brak</string>
<string name="recently_used">Ostatnio używana</string>
<string name="choose_quick_action">Wybierz szybką akcję</string>
</resources> </resources>

View File

@ -448,4 +448,9 @@
<item quantity="few">Изабери %d контакта</item> <item quantity="few">Изабери %d контакта</item>
<item quantity="other">Изабери %d контаката</item> <item quantity="other">Изабери %d контаката</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Замени дугме за слање брзом радњом</string>
<string name="pref_quick_action">Брза радња</string>
<string name="none">Ниједна</string>
<string name="recently_used">Недавно коришћена</string>
<string name="choose_quick_action">Изаберите брзу радњу</string>
</resources> </resources>

View File

@ -446,4 +446,9 @@
<item quantity="one">Välj %d kontakt</item> <item quantity="one">Välj %d kontakt</item>
<item quantity="other">Välj %d kontakter</item> <item quantity="other">Välj %d kontakter</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">Byt sänd-knappen mot snabbfunktion</string>
<string name="pref_quick_action">Snabbfunktion</string>
<string name="none">Ingen</string>
<string name="recently_used">Senast använd</string>
<string name="choose_quick_action">Välj snabbfunktion</string>
</resources> </resources>

View File

@ -444,4 +444,9 @@
<plurals name="select_contact"> <plurals name="select_contact">
<item quantity="other">选择 %d 个联系人</item> <item quantity="other">选择 %d 个联系人</item>
</plurals> </plurals>
<string name="pref_quick_action_summary">以快速动作替代发送按钮</string>
<string name="pref_quick_action">快速动作</string>
<string name="none"></string>
<string name="recently_used">最近使用过的</string>
<string name="choose_quick_action">选择快速动作</string>
</resources> </resources>

View File

@ -44,6 +44,7 @@
<item>@string/none</item> <item>@string/none</item>
<item>@string/recently_used</item> <item>@string/recently_used</item>
<item>@string/attach_take_picture</item> <item>@string/attach_take_picture</item>
<item>@string/attach_choose_picture</item>
<item>@string/attach_record_voice</item> <item>@string/attach_record_voice</item>
<item>@string/send_location</item> <item>@string/send_location</item>
</string-array> </string-array>
@ -52,6 +53,7 @@
<item>none</item> <item>none</item>
<item>recent</item> <item>recent</item>
<item>photo</item> <item>photo</item>
<item>picture</item>
<item>voice</item> <item>voice</item>
<item>location</item> <item>location</item>
</string-array> </string-array>