migrate to xmpp-addr

This commit is contained in:
Daniel Gultsch 2018-03-05 18:30:40 +01:00
parent 0add9a0ea2
commit 1accf9d961
79 changed files with 706 additions and 1040 deletions

View File

@ -53,6 +53,7 @@ dependencies {
implementation 'com.makeramen:roundedimageview:2.3.0' implementation 'com.makeramen:roundedimageview:2.3.0'
implementation "com.wefika:flowlayout:0.4.1" implementation "com.wefika:flowlayout:0.4.1"
implementation 'net.ypresto.androidtranscoder:android-transcoder:0.2.0' implementation 'net.ypresto.androidtranscoder:android-transcoder:0.2.0'
implementation 'rocks.xmpp:xmpp-addr:0.7.5'
} }
ext { ext {

1
proguard-rules.pro vendored
View File

@ -16,3 +16,4 @@
-dontwarn org.bouncycastle.x509.util.LDAPStoreHelper -dontwarn org.bouncycastle.x509.util.LDAPStoreHelper
-dontwarn org.bouncycastle.jce.provider.X509LDAPCertStoreSpi -dontwarn org.bouncycastle.jce.provider.X509LDAPCertStoreSpi
-dontwarn org.bouncycastle.cert.dane.** -dontwarn org.bouncycastle.cert.dane.**
-dontwarn rocks.xmpp.addr.**

View File

@ -39,9 +39,9 @@ public class PgpEngine {
private static void logError(Account account, OpenPgpError error) { private static void logError(Account account, OpenPgpError error) {
if (error != null) { if (error != null) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": OpenKeychain error '" + error.getMessage() + "' code=" + error.getErrorId()); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": OpenKeychain error '" + error.getMessage() + "' code=" + error.getErrorId());
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": OpenKeychain error with no message"); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": OpenKeychain error with no message");
} }
} }
@ -208,7 +208,7 @@ public class PgpEngine {
params.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, account.getPgpId()); params.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, account.getPgpId());
InputStream is = new ByteArrayInputStream(status.getBytes()); InputStream is = new ByteArrayInputStream(status.getBytes());
final OutputStream os = new ByteArrayOutputStream(); final OutputStream os = new ByteArrayOutputStream();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": signing status message \"" + status + "\""); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": signing status message \"" + status + "\"");
api.executeApiAsync(params, is, os, result -> { api.executeApiAsync(params, is, os, result -> {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) { switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: case OpenPgpApi.RESULT_CODE_SUCCESS:

View File

@ -51,11 +51,10 @@ import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded; import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.PublishOptions; import eu.siacs.conversations.xmpp.pep.PublishOptions;
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 rocks.xmpp.addr.Jid;
public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
@ -94,7 +93,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
&& account.getXmppConnection().getFeatures().pep()) { && account.getXmppConnection().getFeatures().pep()) {
publishBundlesIfNeeded(true, false); publishBundlesIfNeeded(true, false);
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping OMEMO initialization"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping OMEMO initialization");
} }
} }
@ -102,7 +101,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
for (Jid jid : jids) { for (Jid jid : jids) {
if (deviceIds.get(jid) != null) { if (deviceIds.get(jid) != null) {
for (Integer foreignId : this.deviceIds.get(jid)) { for (Integer foreignId : this.deviceIds.get(jid)) {
SignalProtocolAddress address = new SignalProtocolAddress(jid.toPreppedString(), foreignId); SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
if (fetchStatusMap.getAll(address.getName()).containsValue(FetchStatus.ERROR)) { if (fetchStatusMap.getAll(address.getName()).containsValue(FetchStatus.ERROR)) {
return true; return true;
} }
@ -113,11 +112,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public void preVerifyFingerprint(Contact contact, String fingerprint) { public void preVerifyFingerprint(Contact contact, String fingerprint) {
axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().toBareJid().toPreppedString(), fingerprint); axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().asBareJid().toString(), fingerprint);
} }
public void preVerifyFingerprint(Account account, String fingerprint) { public void preVerifyFingerprint(Account account, String fingerprint) {
axolotlStore.preVerifyFingerprint(account, account.getJid().toBareJid().toPreppedString(), fingerprint); axolotlStore.preVerifyFingerprint(account, account.getJid().asBareJid().toString(), fingerprint);
} }
public boolean hasVerifiedKeys(String name) { public boolean hasVerifiedKeys(String name) {
@ -202,10 +201,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Bundle information = CryptoHelper.extractCertificateInformation(certificate); Bundle information = CryptoHelper.extractCertificateInformation(certificate);
try { try {
final String cn = information.getString("subject_cn"); final String cn = information.getString("subject_cn");
final Jid jid = Jid.fromString(bareJid); final Jid jid = Jid.of(bareJid);
Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn); Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
account.getRoster().getContact(jid).setCommonName(cn); account.getRoster().getContact(jid).setCommonName(cn);
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
//ignored //ignored
} }
} }
@ -215,8 +214,8 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
private void fillMap(SQLiteAxolotlStore store) { private void fillMap(SQLiteAxolotlStore store) {
List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toPreppedString()); List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().asBareJid().toString());
putDevicesForJid(account.getJid().toBareJid().toPreppedString(), deviceIds, store); putDevicesForJid(account.getJid().asBareJid().toString(), deviceIds, store);
for (String address : store.getKnownAddresses()) { for (String address : store.getKnownAddresses()) {
deviceIds = store.getSubDeviceSessions(address); deviceIds = store.getSubDeviceSessions(address);
putDevicesForJid(address, deviceIds, store); putDevicesForJid(address, deviceIds, store);
@ -247,13 +246,13 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
public void clearErrorFor(Jid jid) { public void clearErrorFor(Jid jid) {
synchronized (MAP_LOCK) { synchronized (MAP_LOCK) {
Map<Integer, FetchStatus> devices = this.map.get(jid.toBareJid().toPreppedString()); Map<Integer, FetchStatus> devices = this.map.get(jid.asBareJid().toString());
if (devices == null) { if (devices == null) {
return; return;
} }
for (Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) { for (Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
if (entry.getValue() == FetchStatus.ERROR) { if (entry.getValue() == FetchStatus.ERROR) {
Log.d(Config.LOGTAG, "resetting error for " + jid.toBareJid() + "(" + entry.getKey() + ")"); Log.d(Config.LOGTAG, "resetting error for " + jid.asBareJid() + "(" + entry.getKey() + ")");
entry.setValue(FetchStatus.TIMEOUT); entry.setValue(FetchStatus.TIMEOUT);
} }
} }
@ -262,7 +261,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public static String getLogprefix(Account account) { public static String getLogprefix(Account account) {
return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): "; return LOGPREFIX + " (" + account.getJid().asBareJid().toString() + "): ";
} }
public AxolotlService(Account account, XmppConnectionService connectionService) { public AxolotlService(Account account, XmppConnectionService connectionService) {
@ -287,28 +286,28 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) { public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toPreppedString(), status); return axolotlStore.getContactKeysWithTrust(account.getJid().asBareJid().toString(), status);
} }
public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) { public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
return axolotlStore.getContactKeysWithTrust(jid.toBareJid().toPreppedString(), status); return axolotlStore.getContactKeysWithTrust(jid.asBareJid().toString(), status);
} }
public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) { public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
Set<IdentityKey> keys = new HashSet<>(); Set<IdentityKey> keys = new HashSet<>();
for (Jid jid : jids) { for (Jid jid : jids) {
keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toPreppedString(), status)); keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toString(), status));
} }
return keys; return keys;
} }
public long getNumTrustedKeys(Jid jid) { public long getNumTrustedKeys(Jid jid) {
return axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()); return axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString());
} }
public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) { public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
for (Jid jid : jids) { for (Jid jid : jids) {
if (axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()) == 0) { if (axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString()) == 0) {
return true; return true;
} }
} }
@ -316,11 +315,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
private SignalProtocolAddress getAddressForJid(Jid jid) { private SignalProtocolAddress getAddressForJid(Jid jid) {
return new SignalProtocolAddress(jid.toPreppedString(), 0); return new SignalProtocolAddress(jid.toString(), 0);
} }
public Collection<XmppAxolotlSession> findOwnSessions() { public Collection<XmppAxolotlSession> findOwnSessions() {
SignalProtocolAddress ownAddress = getAddressForJid(account.getJid().toBareJid()); SignalProtocolAddress ownAddress = getAddressForJid(account.getJid().asBareJid());
ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress.getName()).values()); ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress.getName()).values());
Collections.sort(s); Collections.sort(s);
return s; return s;
@ -373,12 +372,12 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public void destroy() { public void destroy() {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": destroying old axolotl service. no longer in use"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": destroying old axolotl service. no longer in use");
mXmppConnectionService.databaseBackend.wipeAxolotlDb(account); mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
} }
public AxolotlService makeNew() { public AxolotlService makeNew() {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": make new axolotl service"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": make new axolotl service");
return new AxolotlService(this.account, this.mXmppConnectionService); return new AxolotlService(this.account, this.mXmppConnectionService);
} }
@ -387,19 +386,19 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public SignalProtocolAddress getOwnAxolotlAddress() { public SignalProtocolAddress getOwnAxolotlAddress() {
return new SignalProtocolAddress(account.getJid().toBareJid().toPreppedString(), getOwnDeviceId()); return new SignalProtocolAddress(account.getJid().asBareJid().toString(), getOwnDeviceId());
} }
public Set<Integer> getOwnDeviceIds() { public Set<Integer> getOwnDeviceIds() {
return this.deviceIds.get(account.getJid().toBareJid()); return this.deviceIds.get(account.getJid().asBareJid());
} }
public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) { public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
final int hash = deviceIds.hashCode(); final int hash = deviceIds.hashCode();
final boolean me = jid.toBareJid().equals(account.getJid().toBareJid()); final boolean me = jid.asBareJid().equals(account.getJid().asBareJid());
if (me) { if (me) {
if (hash != 0 && hash == this.lastDeviceListNotificationHash) { if (hash != 0 && hash == this.lastDeviceListNotificationHash) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ignoring duplicate own device id list"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring duplicate own device id list");
return; return;
} }
this.lastDeviceListNotificationHash = hash; this.lastDeviceListNotificationHash = hash;
@ -408,10 +407,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (me) { if (me) {
deviceIds.remove(getOwnDeviceId()); deviceIds.remove(getOwnDeviceId());
} }
Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toPreppedString())); Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.asBareJid().toString()));
expiredDevices.removeAll(deviceIds); expiredDevices.removeAll(deviceIds);
for (Integer deviceId : expiredDevices) { for (Integer deviceId : expiredDevices) {
SignalProtocolAddress address = new SignalProtocolAddress(jid.toBareJid().toPreppedString(), deviceId); SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
XmppAxolotlSession session = sessions.get(address); XmppAxolotlSession session = sessions.get(address);
if (session != null && session.getFingerprint() != null) { if (session != null && session.getFingerprint() != null) {
if (session.getTrust().isActive()) { if (session.getTrust().isActive()) {
@ -421,7 +420,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
Set<Integer> newDevices = new HashSet<>(deviceIds); Set<Integer> newDevices = new HashSet<>(deviceIds);
for (Integer deviceId : newDevices) { for (Integer deviceId : newDevices) {
SignalProtocolAddress address = new SignalProtocolAddress(jid.toBareJid().toPreppedString(), deviceId); SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
XmppAxolotlSession session = sessions.get(address); XmppAxolotlSession session = sessions.get(address);
if (session != null && session.getFingerprint() != null) { if (session != null && session.getFingerprint() != null) {
if (!session.getTrust().isActive()) { if (!session.getTrust().isActive()) {
@ -436,7 +435,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
needsPublishing |= this.changeAccessMode.get(); needsPublishing |= this.changeAccessMode.get();
for (Integer deviceId : deviceIds) { for (Integer deviceId : deviceIds) {
SignalProtocolAddress ownDeviceAddress = new SignalProtocolAddress(jid.toBareJid().toPreppedString(), deviceId); SignalProtocolAddress ownDeviceAddress = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
if (sessions.get(ownDeviceAddress) == null) { if (sessions.get(ownDeviceAddress) == null) {
FetchStatus status = fetchStatusMap.get(ownDeviceAddress); FetchStatus status = fetchStatusMap.get(ownDeviceAddress);
if (status == null || status == FetchStatus.TIMEOUT) { if (status == null || status == FetchStatus.TIMEOUT) {
@ -475,7 +474,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... "); Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
return; return;
} }
IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid()); IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().asBareJid());
mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
@ -484,8 +483,8 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} else { } else {
Element item = mXmppConnectionService.getIqParser().getItem(packet); Element item = mXmppConnectionService.getIqParser().getItem(packet);
Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item); Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": retrieved own device list: " + deviceIds); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved own device list: " + deviceIds);
registerDevices(account.getJid().toBareJid(), deviceIds); registerDevices(account.getJid().asBareJid(), deviceIds);
} }
} }
}); });
@ -502,9 +501,9 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) { if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
devices.add(session.getRemoteAddress().getDeviceId()); devices.add(session.getRemoteAddress().getDeviceId());
session.setTrust(session.getTrust().toInactive()); session.setTrust(session.getTrust().toInactive());
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": added own device " + session.getFingerprint() + " to list of expired devices. Last message received " + hours + " hours ago"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": added own device " + session.getFingerprint() + " to list of expired devices. Last message received " + hours + " hours ago");
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": own device " + session.getFingerprint() + " was active " + hours + " hours ago"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": own device " + session.getFingerprint() + " was active " + hours + " hours ago");
} }
} }
} }
@ -543,7 +542,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null; Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null;
if (firstAttempt && error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR)) { if (firstAttempt && error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": precondition wasn't met for device list. pushing node configuration"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for device list. pushing node configuration");
mXmppConnectionService.pushNodeConfiguration(account, AxolotlService.PEP_DEVICE_LIST, publishOptions, new XmppConnectionService.OnConfigurationPushed() { mXmppConnectionService.pushNodeConfiguration(account, AxolotlService.PEP_DEVICE_LIST, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
@Override @Override
public void onPushSucceeded() { public void onPushSucceeded() {
@ -557,7 +556,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
}); });
} else { } else {
if (AxolotlService.this.changeAccessMode.compareAndSet(true, false)) { if (AxolotlService.this.changeAccessMode.compareAndSet(true, false)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done changing access mode"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done changing access mode");
account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, false); account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, false);
mXmppConnectionService.databaseBackend.updateAccount(account); mXmppConnectionService.databaseBackend.updateAccount(account);
} }
@ -618,14 +617,14 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
this.changeAccessMode.set(account.isOptionSet(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE)); this.changeAccessMode.set(account.isOptionSet(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE));
} else { } else {
if (account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true)) { if (account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server doesnt support publish-options. setting for later access mode change"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server doesnt support publish-options. setting for later access mode change");
mXmppConnectionService.databaseBackend.updateAccount(account); mXmppConnectionService.databaseBackend.updateAccount(account);
} }
} }
if (this.changeAccessMode.get()) { if (this.changeAccessMode.get()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server gained publish-options capabilities. changing access model"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server gained publish-options capabilities. changing access model");
} }
IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId()); IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().asBareJid(), getOwnDeviceId());
mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
@ -754,7 +753,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
public void onIqPacketReceived(final Account account, IqPacket packet) { public void onIqPacketReceived(final Account account, IqPacket packet) {
Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null; Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null;
if (firstAttempt && error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR)) { if (firstAttempt && error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": precondition wasn't met for bundle. pushing node configuration"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for bundle. pushing node configuration");
final String node = AxolotlService.PEP_BUNDLES + ":" + getOwnDeviceId(); final String node = AxolotlService.PEP_BUNDLES + ":" + getOwnDeviceId();
mXmppConnectionService.pushNodeConfiguration(account, node, publishOptions, new XmppConnectionService.OnConfigurationPushed() { mXmppConnectionService.pushNodeConfiguration(account, node, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
@Override @Override
@ -821,7 +820,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
final List<Jid> jids; final List<Jid> jids;
if (conversation.getMode() == Conversation.MODE_SINGLE) { if (conversation.getMode() == Conversation.MODE_SINGLE) {
jids = new ArrayList<>(); jids = new ArrayList<>();
jids.add(conversation.getJid().toBareJid()); jids.add(conversation.getJid().asBareJid());
} else { } else {
jids = conversation.getMucOptions().getMembers(); jids = conversation.getMucOptions().getMembers();
} }
@ -845,7 +844,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
final SignalProtocolAddress address = session.getRemoteAddress(); final SignalProtocolAddress address = session.getRemoteAddress();
final IdentityKey identityKey = session.getIdentityKey(); final IdentityKey identityKey = session.getIdentityKey();
try { try {
IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId()); IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.of(address.getName()), address.getDeviceId());
mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
@ -866,10 +865,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]); Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
try { try {
final String cn = information.getString("subject_cn"); final String cn = information.getString("subject_cn");
final Jid jid = Jid.fromString(address.getName()); final Jid jid = Jid.of(address.getName());
Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn); Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
account.getRoster().getContact(jid).setCommonName(cn); account.getRoster().getContact(jid).setCommonName(cn);
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
//ignored //ignored
} }
finishBuildingSessionsFromPEP(address); finishBuildingSessionsFromPEP(address);
@ -888,7 +887,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
finishBuildingSessionsFromPEP(address); finishBuildingSessionsFromPEP(address);
} }
}); });
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
fetchStatusMap.put(address, FetchStatus.SUCCESS); fetchStatusMap.put(address, FetchStatus.SUCCESS);
finishBuildingSessionsFromPEP(address); finishBuildingSessionsFromPEP(address);
} }
@ -897,7 +896,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>(); private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>();
private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) { private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().toBareJid().toPreppedString(), 0); SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName()); Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName());
Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName()); Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName());
if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) { if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
@ -920,7 +919,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
int id = entry.getKey(); int id = entry.getKey();
if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) { if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
publish = true; publish = true;
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error fetching own device with id " + id + ". removing from announcement"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
} }
} }
if (publish) { if (publish) {
@ -952,14 +951,14 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callbacks.add(callback); callbacks.add(callback);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching device ids for " + jid + " already running. adding callback"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid + " already running. adding callback");
} else { } else {
callbacks = new ArrayList<>(); callbacks = new ArrayList<>();
if (callback != null) { if (callback != null) {
callbacks.add(callback); callbacks.add(callback);
} }
this.fetchDeviceIdsMap.put(jid, callbacks); this.fetchDeviceIdsMap.put(jid, callbacks);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching device ids for " + jid); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid);
IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(jid); IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(jid);
mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
@Override @Override
@ -1017,7 +1016,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
try { try {
IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice( IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
Jid.fromString(address.getName()), address.getDeviceId()); Jid.of(address.getName()), address.getDeviceId());
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() { mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
@ -1083,7 +1082,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
}); });
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName()); Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
} }
} }
@ -1094,7 +1093,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
if (deviceIds.get(jid) != null) { if (deviceIds.get(jid) != null) {
for (Integer foreignId : this.deviceIds.get(jid)) { for (Integer foreignId : this.deviceIds.get(jid)) {
SignalProtocolAddress address = new SignalProtocolAddress(jid.toPreppedString(), foreignId); SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
if (sessions.get(address) == null) { if (sessions.get(address) == null) {
IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey(); IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
if (identityKey != null) { if (identityKey != null) {
@ -1116,9 +1115,9 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!"); Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
} }
} }
if (deviceIds.get(account.getJid().toBareJid()) != null) { if (deviceIds.get(account.getJid().asBareJid()) != null) {
for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) { for (Integer ownId : this.deviceIds.get(account.getJid().asBareJid())) {
SignalProtocolAddress address = new SignalProtocolAddress(account.getJid().toBareJid().toPreppedString(), ownId); SignalProtocolAddress address = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownId);
if (sessions.get(address) == null) { if (sessions.get(address) == null) {
IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey(); IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
if (identityKey != null) { if (identityKey != null) {
@ -1126,7 +1125,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey); XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
sessions.put(address, session); sessions.put(address, session);
} else { } else {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().asBareJid() + ":" + ownId);
if (fetchStatusMap.get(address) != FetchStatus.ERROR) { if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
addresses.add(address); addresses.add(address);
} else { } else {
@ -1148,7 +1147,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
iterator.remove(); iterator.remove();
} }
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": createSessionsIfNeeded() - jids with empty device list: " + jidsWithEmptyDeviceList); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": createSessionsIfNeeded() - jids with empty device list: " + jidsWithEmptyDeviceList);
if (jidsWithEmptyDeviceList.size() > 0) { if (jidsWithEmptyDeviceList.size() > 0) {
fetchDeviceIds(jidsWithEmptyDeviceList, new OnMultipleDeviceIdFetched() { fetchDeviceIds(jidsWithEmptyDeviceList, new OnMultipleDeviceIdFetched() {
@Override @Override
@ -1201,13 +1200,13 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
public boolean hasPendingKeyFetches(Account account, List<Jid> jids) { public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().toBareJid().toPreppedString(), 0); SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
if (fetchStatusMap.getAll(ownAddress.getName()).containsValue(FetchStatus.PENDING)) { if (fetchStatusMap.getAll(ownAddress.getName()).containsValue(FetchStatus.PENDING)) {
return true; return true;
} }
synchronized (this.fetchDeviceIdsMap) { synchronized (this.fetchDeviceIdsMap) {
for (Jid jid : jids) { for (Jid jid : jids) {
SignalProtocolAddress foreignAddress = new SignalProtocolAddress(jid.toBareJid().toPreppedString(), 0); SignalProtocolAddress foreignAddress = new SignalProtocolAddress(jid.asBareJid().toString(), 0);
if (fetchStatusMap.getAll(foreignAddress.getName()).containsValue(FetchStatus.PENDING) || this.fetchDeviceIdsMap.containsKey(jid)) { if (fetchStatusMap.getAll(foreignAddress.getName()).containsValue(FetchStatus.PENDING) || this.fetchDeviceIdsMap.containsKey(jid)) {
return true; return true;
} }
@ -1253,7 +1252,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
@Nullable @Nullable
public XmppAxolotlMessage encrypt(Message message) { public XmppAxolotlMessage encrypt(Message message) {
final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId()); final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
final String content; final String content;
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
content = message.getFileParams().url.toString(); content = message.getFileParams().url.toString();
@ -1297,7 +1296,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId()); final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
if (buildHeader(axolotlMessage, conversation)) { if (buildHeader(axolotlMessage, conversation)) {
onMessageCreatedCallback.run(axolotlMessage); onMessageCreatedCallback.run(axolotlMessage);
} else { } else {
@ -1326,7 +1325,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) { private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
SignalProtocolAddress senderAddress = new SignalProtocolAddress(message.getFrom().toPreppedString(), SignalProtocolAddress senderAddress = new SignalProtocolAddress(message.getFrom().toString(),
message.getSenderDeviceId()); message.getSenderDeviceId());
XmppAxolotlSession session = sessions.get(senderAddress); XmppAxolotlSession session = sessions.get(senderAddress);
if (session == null) { if (session == null) {
@ -1382,13 +1381,13 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
private void completeSession(XmppAxolotlSession session) { private void completeSession(XmppAxolotlSession session) {
final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId()); final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
axolotlMessage.addDevice(session); axolotlMessage.addDevice(session);
try { try {
Jid jid = Jid.fromString(session.getRemoteAddress().getName()); Jid jid = Jid.of(session.getRemoteAddress().getName());
MessagePacket packet = mXmppConnectionService.getMessageGenerator().generateKeyTransportMessage(jid, axolotlMessage); MessagePacket packet = mXmppConnectionService.getMessageGenerator().generateKeyTransportMessage(jid, axolotlMessage);
mXmppConnectionService.sendMessagePacket(account, packet); mXmppConnectionService.sendMessagePacket(account, packet);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
throw new Error("Remote addresses are created from jid and should convert back to jid", e); throw new Error("Remote addresses are created from jid and should convert back to jid", e);
} }
} }
@ -1423,7 +1422,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (session.getIdentityKey() != null) { if (session.getIdentityKey() != null) {
verifySessionWithPEP(session); verifySessionWithPEP(session);
} else { } else {
Log.e(Config.LOGTAG, account.getJid().toBareJid() + ": identity key was empty after reloading for x509 verification"); Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": identity key was empty after reloading for x509 verification");
} }
} }
} }

View File

@ -191,7 +191,7 @@ public class SQLiteAxolotlStore implements SignalProtocolStore {
FingerprintStatus status = getFingerprintStatus(fingerprint); FingerprintStatus status = getFingerprintStatus(fingerprint);
if (status == null) { if (status == null) {
if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(address.getName())) { if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(address.getName())) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": blindly trusted "+fingerprint+" of "+address.getName()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": blindly trusted "+fingerprint+" of "+address.getName());
status = FingerprintStatus.createActiveTrusted(); status = FingerprintStatus.createActiveTrusted();
} else { } else {
status = FingerprintStatus.createActiveUndecided(); status = FingerprintStatus.createActiveUndecided();

View File

@ -25,7 +25,7 @@ import javax.crypto.spec.SecretKeySpec;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class XmppAxolotlMessage { public class XmppAxolotlMessage {
public static final String CONTAINERTAG = "encrypted"; public static final String CONTAINERTAG = "encrypted";

View File

@ -24,6 +24,6 @@ public class External extends SaslMechanism {
@Override @Override
public String getClientFirstMessage() { public String getClientFirstMessage() {
return Base64.encodeToString(account.getJid().toBareJid().toString().getBytes(),Base64.NO_WRAP); return Base64.encodeToString(account.getJid().asBareJid().toString().getBytes(),Base64.NO_WRAP);
} }
} }

View File

@ -149,7 +149,7 @@ abstract class ScramMechanism extends SaslMechanism {
// Map keys are "bytesToHex(JID),bytesToHex(password),bytesToHex(salt),iterations". // Map keys are "bytesToHex(JID),bytesToHex(password),bytesToHex(salt),iterations".
final KeyPair keys = CACHE.get( final KeyPair keys = CACHE.get(
CryptoHelper.bytesToHex(account.getJid().toBareJid().toString().getBytes()) + "," CryptoHelper.bytesToHex(account.getJid().asBareJid().toString().getBytes()) + ","
+ CryptoHelper.bytesToHex(account.getPassword().getBytes()) + "," + CryptoHelper.bytesToHex(account.getPassword().getBytes()) + ","
+ CryptoHelper.bytesToHex(salt.getBytes()) + "," + CryptoHelper.bytesToHex(salt.getBytes()) + ","
+ String.valueOf(iterationCount) + String.valueOf(iterationCount)

View File

@ -3,8 +3,10 @@ package eu.siacs.conversations.entities;
import android.content.ContentValues; import android.content.ContentValues;
import android.database.Cursor; import android.database.Cursor;
import android.os.SystemClock; import android.os.SystemClock;
import android.util.Log;
import android.util.Pair; import android.util.Pair;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.crypto.PgpDecryptionService; import eu.siacs.conversations.crypto.PgpDecryptionService;
import org.json.JSONException; import org.json.JSONException;
@ -23,8 +25,7 @@ import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class Account extends AbstractEntity { public class Account extends AbstractEntity {
@ -276,13 +277,16 @@ public class Account extends AbstractEntity {
} }
public static Account fromCursor(final Cursor cursor) { public static Account fromCursor(final Cursor cursor) {
Jid jid = null; final Jid jid;
try { try {
jid = Jid.fromParts( String resource = cursor.getString(cursor.getColumnIndex(RESOURCE));
jid = Jid.of(
cursor.getString(cursor.getColumnIndex(USERNAME)), cursor.getString(cursor.getColumnIndex(USERNAME)),
cursor.getString(cursor.getColumnIndex(SERVER)), cursor.getString(cursor.getColumnIndex(SERVER)),
cursor.getString(cursor.getColumnIndex(RESOURCE))); resource == null || resource.trim().isEmpty() ? null : resource);
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
Log.d(Config.LOGTAG,cursor.getString(cursor.getColumnIndex(USERNAME))+"@"+cursor.getString(cursor.getColumnIndex(SERVER)));
throw new AssertionError(ignored);
} }
return new Account(cursor.getString(cursor.getColumnIndex(UUID)), return new Account(cursor.getString(cursor.getColumnIndex(UUID)),
jid, jid,
@ -313,13 +317,13 @@ public class Account extends AbstractEntity {
} }
public String getUsername() { public String getUsername() {
return jid.getLocalpart(); return jid.getLocal();
} }
public boolean setJid(final Jid next) { public boolean setJid(final Jid next) {
final Jid previousFull = this.jid; final Jid previousFull = this.jid;
final Jid prev = this.jid != null ? this.jid.toBareJid() : null; final Jid prev = this.jid != null ? this.jid.asBareJid() : null;
final boolean changed = prev == null || (next != null && !prev.equals(next.toBareJid())); final boolean changed = prev == null || (next != null && !prev.equals(next.asBareJid()));
if (changed) { if (changed) {
final AxolotlService oldAxolotlService = this.axolotlService; final AxolotlService oldAxolotlService = this.axolotlService;
if (oldAxolotlService != null) { if (oldAxolotlService != null) {
@ -329,11 +333,11 @@ public class Account extends AbstractEntity {
} }
} }
this.jid = next; this.jid = next;
return next != null && next.equals(previousFull); return next != null && !next.equals(previousFull);
} }
public Jid getServer() { public Jid getServer() {
return jid.toDomainJid(); return Jid.ofDomain(jid.getDomain());
} }
public String getPassword() { public String getPassword() {
@ -408,20 +412,11 @@ public class Account extends AbstractEntity {
} }
public String getResource() { public String getResource() {
return jid.getResourcepart(); return jid.getResource();
} }
public boolean setResource(final String resource) { public void setResource(final String resource) {
final String oldResource = jid.getResourcepart(); this.jid = this.jid.withResource(resource);
if (oldResource == null || !oldResource.equals(resource)) {
try {
jid = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), resource);
return true;
} catch (final InvalidJidException ignored) {
return true;
}
}
return false;
} }
public Jid getJid() { public Jid getJid() {
@ -470,8 +465,8 @@ public class Account extends AbstractEntity {
public ContentValues getContentValues() { public ContentValues getContentValues() {
final ContentValues values = new ContentValues(); final ContentValues values = new ContentValues();
values.put(UUID, uuid); values.put(UUID, uuid);
values.put(USERNAME, jid.getLocalpart()); values.put(USERNAME, jid.getLocal());
values.put(SERVER, jid.getDomainpart()); values.put(SERVER, jid.getDomain());
values.put(PASSWORD, password); values.put(PASSWORD, password);
values.put(OPTIONS, options); values.put(OPTIONS, options);
synchronized (this.keys) { synchronized (this.keys) {
@ -484,7 +479,7 @@ public class Account extends AbstractEntity {
values.put(PORT, port); values.put(PORT, port);
values.put(STATUS, presenceStatus.toShowString()); values.put(STATUS, presenceStatus.toShowString());
values.put(STATUS_MESSAGE, presenceStatusMessage); values.put(STATUS_MESSAGE, presenceStatusMessage);
values.put(RESOURCE,jid.getResourcepart()); values.put(RESOURCE,jid.getResource());
return values; return values;
} }
@ -589,7 +584,7 @@ public class Account extends AbstractEntity {
public Bookmark getBookmark(final Jid jid) { public Bookmark getBookmark(final Jid jid) {
for(final Bookmark bookmark : this.bookmarks) { for(final Bookmark bookmark : this.bookmarks) {
if (bookmark.getJid() != null && jid.toBareJid().equals(bookmark.getJid().toBareJid())) { if (bookmark.getJid() != null && jid.asBareJid().equals(bookmark.getJid().asBareJid())) {
return bookmark; return bookmark;
} }
} }
@ -623,7 +618,7 @@ public class Account extends AbstractEntity {
public String getShareableUri() { public String getShareableUri() {
List<XmppUri.Fingerprint> fingerprints = this.getFingerprints(); List<XmppUri.Fingerprint> fingerprints = this.getFingerprints();
String uri = "xmpp:"+this.getJid().toBareJid().toString(); String uri = "xmpp:"+this.getJid().asBareJid().toString();
if (fingerprints.size() > 0) { if (fingerprints.size() > 0) {
return XmppUri.getFingerprintUri(uri,fingerprints,';'); return XmppUri.getFingerprintUri(uri,fingerprints,';');
} else { } else {
@ -633,7 +628,7 @@ public class Account extends AbstractEntity {
public String getShareableLink() { public String getShareableLink() {
List<XmppUri.Fingerprint> fingerprints = this.getFingerprints(); List<XmppUri.Fingerprint> fingerprints = this.getFingerprints();
String uri = "https://conversations.im/i/"+this.getJid().toBareJid().toString(); String uri = "https://conversations.im/i/"+this.getJid().asBareJid().toString();
if (fingerprints.size() > 0) { if (fingerprints.size() > 0) {
return XmppUri.getFingerprintUri(uri,fingerprints,'&'); return XmppUri.getFingerprintUri(uri,fingerprints,'&');
} else { } else {
@ -657,11 +652,11 @@ public class Account extends AbstractEntity {
public boolean isBlocked(final ListItem contact) { public boolean isBlocked(final ListItem contact) {
final Jid jid = contact.getJid(); final Jid jid = contact.getJid();
return jid != null && (blocklist.contains(jid.toBareJid()) || blocklist.contains(jid.toDomainJid())); return jid != null && (blocklist.contains(jid.asBareJid()) || blocklist.contains(Jid.ofDomain(jid.getDomain())));
} }
public boolean isBlocked(final Jid jid) { public boolean isBlocked(final Jid jid) {
return jid != null && blocklist.contains(jid.toBareJid()); return jid != null && blocklist.contains(jid.asBareJid());
} }
public Collection<Jid> getBlocklist() { public Collection<Jid> getBlocklist() {

View File

@ -1,6 +1,6 @@
package eu.siacs.conversations.entities; package eu.siacs.conversations.entities;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public interface Blockable { public interface Blockable {
boolean isBlocked(); boolean isBlocked();

View File

@ -9,7 +9,7 @@ import java.util.Locale;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class Bookmark extends Element implements ListItem { public class Bookmark extends Element implements ListItem {
@ -58,7 +58,7 @@ public class Bookmark extends Element implements ListItem {
return getBookmarkName().trim(); return getBookmarkName().trim();
} else { } else {
Jid jid = this.getJid(); Jid jid = this.getJid();
String name = jid != null ? jid.getLocalpart() : getAttribute("jid"); String name = jid != null ? jid.getLocal() : getAttribute("jid");
return name != null ? name : ""; return name != null ? name : "";
} }
} }

View File

@ -18,9 +18,8 @@ import eu.siacs.conversations.Config;
import eu.siacs.conversations.utils.JidHelper; import eu.siacs.conversations.utils.JidHelper;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import rocks.xmpp.addr.Jid;
public class Contact implements ListItem, Blockable { public class Contact implements ListItem, Blockable {
public static final String TABLENAME = "contacts"; public static final String TABLENAME = "contacts";
@ -93,8 +92,8 @@ public class Contact implements ListItem, Blockable {
public static Contact fromCursor(final Cursor cursor) { public static Contact fromCursor(final Cursor cursor) {
final Jid jid; final Jid jid;
try { try {
jid = Jid.fromString(cursor.getString(cursor.getColumnIndex(JID)), true); jid = Jid.of(cursor.getString(cursor.getColumnIndex(JID)));
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
// TODO: Borked DB... handle this somehow? // TODO: Borked DB... handle this somehow?
return null; return null;
} }
@ -121,10 +120,10 @@ public class Contact implements ListItem, Blockable {
return this.serverName; return this.serverName;
} else if (this.presenceName != null && !this.presenceName.isEmpty() && mutualPresenceSubscription() ) { } else if (this.presenceName != null && !this.presenceName.isEmpty() && mutualPresenceSubscription() ) {
return this.presenceName; return this.presenceName;
} else if (jid.hasLocalpart()) { } else if (jid.getLocal() != null) {
return JidHelper.localPartOrFallback(jid); return JidHelper.localPartOrFallback(jid);
} else { } else {
return jid.getDomainpart(); return jid.getDomain();
} }
} }
@ -197,7 +196,7 @@ public class Contact implements ListItem, Blockable {
values.put(ACCOUNT, accountUuid); values.put(ACCOUNT, accountUuid);
values.put(SYSTEMNAME, systemName); values.put(SYSTEMNAME, systemName);
values.put(SERVERNAME, serverName); values.put(SERVERNAME, serverName);
values.put(JID, jid.toPreppedString()); values.put(JID, jid.toString());
values.put(OPTIONS, subscription); values.put(OPTIONS, subscription);
values.put(SYSTEMACCOUNT, systemAccount); values.put(SYSTEMACCOUNT, systemAccount);
values.put(PHOTOURI, photoUri); values.put(PHOTOURI, photoUri);
@ -445,7 +444,7 @@ public class Contact implements ListItem, Blockable {
} }
public Jid getServer() { public Jid getServer() {
return getJid().toDomainJid(); return Jid.ofDomain(getJid().getDomain());
} }
public boolean setAvatar(Avatar avatar) { public boolean setAvatar(Avatar avatar) {
@ -499,20 +498,20 @@ public class Contact implements ListItem, Blockable {
@Override @Override
public boolean isDomainBlocked() { public boolean isDomainBlocked() {
return getAccount().isBlocked(this.getJid().toDomainJid()); return getAccount().isBlocked(Jid.ofDomain(this.getJid().getDomain()));
} }
@Override @Override
public Jid getBlockedJid() { public Jid getBlockedJid() {
if (isDomainBlocked()) { if (isDomainBlocked()) {
return getJid().toDomainJid(); return Jid.ofDomain(getJid().getDomain());
} else { } else {
return getJid(); return getJid();
} }
} }
public boolean isSelf() { public boolean isSelf() {
return account.getJid().toBareJid().equals(getJid().toBareJid()); return account.getJid().asBareJid().equals(getJid().asBareJid());
} }
public void setCommonName(String cn) { public void setCommonName(String cn) {

View File

@ -21,9 +21,8 @@ import eu.siacs.conversations.Config;
import eu.siacs.conversations.crypto.PgpDecryptionService; import eu.siacs.conversations.crypto.PgpDecryptionService;
import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.AxolotlService;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.mam.MamReference; import eu.siacs.conversations.xmpp.mam.MamReference;
import rocks.xmpp.addr.Jid;
public class Conversation extends AbstractEntity implements Blockable, Comparable<Conversation> { public class Conversation extends AbstractEntity implements Blockable, Comparable<Conversation> {
@ -350,7 +349,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
public List<Jid> getAcceptedCryptoTargets() { public List<Jid> getAcceptedCryptoTargets() {
if (mode == MODE_SINGLE) { if (mode == MODE_SINGLE) {
return Collections.singletonList(getJid().toBareJid()); return Collections.singletonList(getJid().asBareJid());
} else { } else {
return getJidListAttribute(ATTRIBUTE_CRYPTO_TARGETS); return getJidListAttribute(ATTRIBUTE_CRYPTO_TARGETS);
} }
@ -482,11 +481,11 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
if (generatedName != null) { if (generatedName != null) {
return generatedName; return generatedName;
} else { } else {
return getJid().getUnescapedLocalpart(); return getJid().getLocal();
} }
} }
} else if (isWithStranger()) { } else if (isWithStranger()) {
return contactJid.toBareJid().toString(); return contactJid.asBareJid().toString();
} else { } else {
return this.getContact().getDisplayName(); return this.getContact().getDisplayName();
} }
@ -527,7 +526,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
values.put(NAME, name); values.put(NAME, name);
values.put(CONTACT, contactUuid); values.put(CONTACT, contactUuid);
values.put(ACCOUNT, accountUuid); values.put(ACCOUNT, accountUuid);
values.put(CONTACTJID, contactJid.toPreppedString()); values.put(CONTACTJID, contactJid.toString());
values.put(CREATED, created); values.put(CREATED, created);
values.put(STATUS, status); values.put(STATUS, status);
values.put(MODE, mode); values.put(MODE, mode);
@ -538,8 +537,8 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
public static Conversation fromCursor(Cursor cursor) { public static Conversation fromCursor(Cursor cursor) {
Jid jid; Jid jid;
try { try {
jid = Jid.fromString(cursor.getString(cursor.getColumnIndex(CONTACTJID)), true); jid = Jid.of(cursor.getString(cursor.getColumnIndex(CONTACTJID)));
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
// Borked DB.. // Borked DB..
jid = null; jid = null;
} }
@ -739,7 +738,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
public boolean setAttribute(String key, List<Jid> jids) { public boolean setAttribute(String key, List<Jid> jids) {
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
for(Jid jid : jids) { for(Jid jid : jids) {
array.put(jid.toBareJid().toString()); array.put(jid.asBareJid().toString());
} }
synchronized (this.attributes) { synchronized (this.attributes) {
try { try {
@ -769,8 +768,8 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
JSONArray array = this.attributes.getJSONArray(key); JSONArray array = this.attributes.getJSONArray(key);
for (int i = 0; i < array.length(); ++i) { for (int i = 0; i < array.length(); ++i) {
try { try {
list.add(Jid.fromString(array.getString(i))); list.add(Jid.of(array.getString(i)));
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
//ignored //ignored
} }
} }
@ -906,7 +905,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
public boolean isWithStranger() { public boolean isWithStranger() {
return mode == MODE_SINGLE return mode == MODE_SINGLE
&& !getJid().equals(account.getJid().toDomainJid()) && !getJid().equals(Jid.ofDomain(account.getJid().getDomain()))
&& !getContact().showInRoster() && !getContact().showInRoster()
&& sentMessagesCount() == 0; && sentMessagesCount() == 0;
} }

View File

@ -4,7 +4,8 @@ import android.content.Context;
import java.util.List; import java.util.List;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public interface ListItem extends Comparable<ListItem> { public interface ListItem extends Comparable<ListItem> {
String getDisplayName(); String getDisplayName();

View File

@ -3,10 +3,6 @@ package eu.siacs.conversations.entities;
import android.content.ContentValues; import android.content.ContentValues;
import android.database.Cursor; import android.database.Cursor;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@ -25,8 +21,7 @@ import eu.siacs.conversations.utils.Emoticons;
import eu.siacs.conversations.utils.GeoHelper; import eu.siacs.conversations.utils.GeoHelper;
import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.utils.MimeUtils;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class Message extends AbstractEntity { public class Message extends AbstractEntity {
@ -118,7 +113,7 @@ public class Message extends AbstractEntity {
public Message(Conversation conversation, String body, int encryption, int status) { public Message(Conversation conversation, String body, int encryption, int status) {
this(conversation, java.util.UUID.randomUUID().toString(), this(conversation, java.util.UUID.randomUUID().toString(),
conversation.getUuid(), conversation.getUuid(),
conversation.getJid() == null ? null : conversation.getJid().toBareJid(), conversation.getJid() == null ? null : conversation.getJid().asBareJid(),
null, null,
body, body,
System.currentTimeMillis(), System.currentTimeMillis(),
@ -173,11 +168,11 @@ public class Message extends AbstractEntity {
try { try {
String value = cursor.getString(cursor.getColumnIndex(COUNTERPART)); String value = cursor.getString(cursor.getColumnIndex(COUNTERPART));
if (value != null) { if (value != null) {
jid = Jid.fromString(value, true); jid = Jid.of(value);
} else { } else {
jid = null; jid = null;
} }
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
jid = null; jid = null;
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return null; // message too long? return null; // message too long?
@ -186,11 +181,11 @@ public class Message extends AbstractEntity {
try { try {
String value = cursor.getString(cursor.getColumnIndex(TRUE_COUNTERPART)); String value = cursor.getString(cursor.getColumnIndex(TRUE_COUNTERPART));
if (value != null) { if (value != null) {
trueCounterpart = Jid.fromString(value, true); trueCounterpart = Jid.of(value);
} else { } else {
trueCounterpart = null; trueCounterpart = null;
} }
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
trueCounterpart = null; trueCounterpart = null;
} }
return new Message(conversation, return new Message(conversation,
@ -247,12 +242,12 @@ public class Message extends AbstractEntity {
if (counterpart == null) { if (counterpart == null) {
values.putNull(COUNTERPART); values.putNull(COUNTERPART);
} else { } else {
values.put(COUNTERPART, counterpart.toPreppedString()); values.put(COUNTERPART, counterpart.toString());
} }
if (trueCounterpart == null) { if (trueCounterpart == null) {
values.putNull(TRUE_COUNTERPART); values.putNull(TRUE_COUNTERPART);
} else { } else {
values.put(TRUE_COUNTERPART, trueCounterpart.toPreppedString()); values.put(TRUE_COUNTERPART, trueCounterpart.toString());
} }
values.put(BODY, body.length() > Config.MAX_STORAGE_MESSAGE_CHARS ? body.substring(0,Config.MAX_STORAGE_MESSAGE_CHARS) : body); values.put(BODY, body.length() > Config.MAX_STORAGE_MESSAGE_CHARS ? body.substring(0,Config.MAX_STORAGE_MESSAGE_CHARS) : body);
values.put(TIME_SENT, timeSent); values.put(TIME_SENT, timeSent);
@ -439,7 +434,7 @@ public class Message extends AbstractEntity {
public boolean addReadByMarker(ReadByMarker readByMarker) { public boolean addReadByMarker(ReadByMarker readByMarker) {
if (readByMarker.getRealJid() != null) { if (readByMarker.getRealJid() != null) {
if (readByMarker.getRealJid().toBareJid().equals(trueCounterpart)) { if (readByMarker.getRealJid().asBareJid().equals(trueCounterpart)) {
return false; return false;
} }
} else if (readByMarker.getFullJid() != null) { } else if (readByMarker.getFullJid() != null) {
@ -569,7 +564,7 @@ public class Message extends AbstractEntity {
((this.axolotlFingerprint == null && message.axolotlFingerprint == null) || this.axolotlFingerprint.equals(message.getFingerprint())) && ((this.axolotlFingerprint == null && message.axolotlFingerprint == null) || this.axolotlFingerprint.equals(message.getFingerprint())) &&
UIHelper.sameDay(message.getTimeSent(),this.getTimeSent()) && UIHelper.sameDay(message.getTimeSent(),this.getTimeSent()) &&
this.getReadByMarkers().equals(message.getReadByMarkers()) && this.getReadByMarkers().equals(message.getReadByMarkers()) &&
!this.conversation.getJid().toBareJid().toString().equals(Config.BUG_REPORTS) !this.conversation.getJid().asBareJid().toString().equals(Config.BUG_REPORTS)
); );
} }
@ -651,15 +646,15 @@ public class Message extends AbstractEntity {
public boolean fixCounterpart() { public boolean fixCounterpart() {
Presences presences = conversation.getContact().getPresences(); Presences presences = conversation.getContact().getPresences();
if (counterpart != null && presences.has(counterpart.getResourcepart())) { if (counterpart != null && presences.has(counterpart.getResource())) {
return true; return true;
} else if (presences.size() >= 1) { } else if (presences.size() >= 1) {
try { try {
counterpart = Jid.fromParts(conversation.getJid().getLocalpart(), counterpart = Jid.of(conversation.getJid().getLocal(),
conversation.getJid().getDomainpart(), conversation.getJid().getDomain(),
presences.toResourceArray()[0]); presences.toResourceArray()[0]);
return true; return true;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
counterpart = null; counterpart = null;
return false; return false;
} }

View File

@ -15,9 +15,8 @@ import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.forms.Field; import eu.siacs.conversations.xmpp.forms.Field;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import rocks.xmpp.addr.Jid;
@SuppressLint("DefaultLocale") @SuppressLint("DefaultLocale")
public class MucOptions { public class MucOptions {
@ -179,11 +178,11 @@ public class MucOptions {
} }
public String getName() { public String getName() {
return fullJid == null ? null : fullJid.getResourcepart(); return fullJid == null ? null : fullJid.getResource();
} }
public void setRealJid(Jid jid) { public void setRealJid(Jid jid) {
this.realJid = jid != null ? jid.toBareJid() : null; this.realJid = jid != null ? jid.asBareJid() : null;
} }
public Role getRole() { public Role getRole() {
@ -319,7 +318,7 @@ public class MucOptions {
} }
public boolean realJidMatchesAccount() { public boolean realJidMatchesAccount() {
return realJid != null && realJid.equals(options.account.getJid().toBareJid()); return realJid != null && realJid.equals(options.account.getJid().asBareJid());
} }
@Override @Override
@ -448,7 +447,7 @@ public class MucOptions {
break; break;
} }
} }
boolean self = user.realJid != null && user.realJid.equals(account.getJid().toBareJid()); boolean self = user.realJid != null && user.realJid.equals(account.getJid().asBareJid());
if (membersOnly() if (membersOnly()
&& nonanonymous() && nonanonymous()
&& user.affiliation.ranks(Affiliation.MEMBER) && user.affiliation.ranks(Affiliation.MEMBER)
@ -536,7 +535,7 @@ public class MucOptions {
public User findUser(ReadByMarker readByMarker) { public User findUser(ReadByMarker readByMarker) {
if (readByMarker.getRealJid() != null) { if (readByMarker.getRealJid() != null) {
User user = findUserByRealJid(readByMarker.getRealJid().toBareJid()); User user = findUserByRealJid(readByMarker.getRealJid().asBareJid());
if (user == null) { if (user == null) {
user = new User(this,readByMarker.getFullJid()); user = new User(this,readByMarker.getFullJid());
user.setRealJid(readByMarker.getRealJid()); user.setRealJid(readByMarker.getRealJid());
@ -550,7 +549,7 @@ public class MucOptions {
} }
public boolean isContactInRoom(Contact contact) { public boolean isContactInRoom(Contact contact) {
return findUserByRealJid(contact.getJid().toBareJid()) != null; return findUserByRealJid(contact.getJid().asBareJid()) != null;
} }
public boolean isUserInRoom(Jid jid) { public boolean isUserInRoom(Jid jid) {
@ -606,7 +605,7 @@ public class MucOptions {
public List<User> getUsers(int max) { public List<User> getUsers(int max) {
ArrayList<User> subset = new ArrayList<>(); ArrayList<User> subset = new ArrayList<>();
HashSet<Jid> jids = new HashSet<>(); HashSet<Jid> jids = new HashSet<>();
jids.add(account.getJid().toBareJid()); jids.add(account.getJid().asBareJid());
synchronized (users) { synchronized (users) {
for(User user : users) { for(User user : users) {
if (user.getRealJid() == null || jids.add(user.getRealJid())) { if (user.getRealJid() == null || jids.add(user.getRealJid())) {
@ -632,7 +631,7 @@ public class MucOptions {
&& !conversation.getBookmark().getNick().trim().isEmpty()) { && !conversation.getBookmark().getNick().trim().isEmpty()) {
return conversation.getBookmark().getNick().trim(); return conversation.getBookmark().getNick().trim();
} else if (!conversation.getJid().isBareJid()) { } else if (!conversation.getJid().isBareJid()) {
return conversation.getJid().getResourcepart(); return conversation.getJid().getResource();
} else { } else {
return JidHelper.localPartOrFallback(account.getJid()); return JidHelper.localPartOrFallback(account.getJid());
} }
@ -756,15 +755,15 @@ public class MucOptions {
public Jid createJoinJid(String nick) { public Jid createJoinJid(String nick) {
try { try {
return Jid.fromString(this.conversation.getJid().toBareJid().toString() + "/" + nick); return Jid.of(this.conversation.getJid().asBareJid().toString() + "/" + nick);
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
return null; return null;
} }
} }
public Jid getTrueCounterpart(Jid jid) { public Jid getTrueCounterpart(Jid jid) {
if (jid.equals(getSelf().getFullJid())) { if (jid.equals(getSelf().getFullJid())) {
return account.getJid().toBareJid(); return account.getJid().asBareJid();
} }
User user = findUserByFullJid(jid); User user = findUserByFullJid(jid);
return user == null ? null : user.realJid; return user == null ? null : user.realJid;

View File

@ -8,8 +8,7 @@ import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ReadByMarker { public class ReadByMarker {
@ -52,14 +51,14 @@ public class ReadByMarker {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
if (fullJid != null) { if (fullJid != null) {
try { try {
jsonObject.put("fullJid", fullJid.toPreppedString()); jsonObject.put("fullJid", fullJid.toString());
} catch (JSONException e) { } catch (JSONException e) {
//ignore //ignore
} }
} }
if (realJid != null) { if (realJid != null) {
try { try {
jsonObject.put("realJid", realJid.toPreppedString()); jsonObject.put("realJid", realJid.toString());
} catch (JSONException e) { } catch (JSONException e) {
//ignore //ignore
} }
@ -82,7 +81,7 @@ public class ReadByMarker {
public static ReadByMarker from(Jid fullJid, Jid realJid) { public static ReadByMarker from(Jid fullJid, Jid realJid) {
final ReadByMarker marker = new ReadByMarker(); final ReadByMarker marker = new ReadByMarker();
marker.fullJid = fullJid; marker.fullJid = fullJid;
marker.realJid = realJid == null ? null : realJid.toBareJid(); marker.realJid = realJid == null ? null : realJid.asBareJid();
return marker; return marker;
} }
@ -111,13 +110,13 @@ public class ReadByMarker {
public static ReadByMarker fromJson(JSONObject jsonObject) { public static ReadByMarker fromJson(JSONObject jsonObject) {
ReadByMarker marker = new ReadByMarker(); ReadByMarker marker = new ReadByMarker();
try { try {
marker.fullJid = Jid.fromString(jsonObject.getString("fullJid"),true); marker.fullJid = Jid.of(jsonObject.getString("fullJid"));
} catch (JSONException | InvalidJidException e) { } catch (JSONException | IllegalArgumentException e) {
marker.fullJid = null; marker.fullJid = null;
} }
try { try {
marker.realJid = Jid.fromString(jsonObject.getString("realJid"),true); marker.realJid = Jid.of(jsonObject.getString("realJid"));
} catch (JSONException | InvalidJidException e) { } catch (JSONException | IllegalArgumentException e) {
marker.realJid = null; marker.realJid = null;
} }
return marker; return marker;
@ -142,7 +141,7 @@ public class ReadByMarker {
public static boolean contains(ReadByMarker needle, Set<ReadByMarker> readByMarkers) { public static boolean contains(ReadByMarker needle, Set<ReadByMarker> readByMarkers) {
for(ReadByMarker marker : readByMarkers) { for(ReadByMarker marker : readByMarkers) {
if (marker.realJid != null && needle.realJid != null) { if (marker.realJid != null && needle.realJid != null) {
if (marker.realJid.toBareJid().equals(needle.realJid.toBareJid())) { if (marker.realJid.asBareJid().equals(needle.realJid.asBareJid())) {
return true; return true;
} }
} else if (marker.fullJid != null && needle.fullJid != null) { } else if (marker.fullJid != null && needle.fullJid != null) {

View File

@ -29,7 +29,7 @@
package eu.siacs.conversations.entities; package eu.siacs.conversations.entities;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class ReceiptRequest { public class ReceiptRequest {
@ -43,7 +43,7 @@ public class ReceiptRequest {
if (jid == null) { if (jid == null) {
throw new IllegalArgumentException("jid must not be null"); throw new IllegalArgumentException("jid must not be null");
} }
this.jid = jid.toBareJid(); this.jid = jid.asBareJid();
this.id = id; this.id = id;
} }

View File

@ -5,7 +5,8 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class Roster { public class Roster {
final Account account; final Account account;
@ -21,7 +22,7 @@ public class Roster {
return null; return null;
} }
synchronized (this.contacts) { synchronized (this.contacts) {
Contact contact = contacts.get(jid.toBareJid()); Contact contact = contacts.get(jid.asBareJid());
if (contact != null && contact.showInRoster()) { if (contact != null && contact.showInRoster()) {
return contact; return contact;
} else { } else {
@ -32,13 +33,13 @@ public class Roster {
public Contact getContact(final Jid jid) { public Contact getContact(final Jid jid) {
synchronized (this.contacts) { synchronized (this.contacts) {
if (!contacts.containsKey(jid.toBareJid())) { if (!contacts.containsKey(jid.asBareJid())) {
Contact contact = new Contact(jid.toBareJid()); Contact contact = new Contact(jid.asBareJid());
contact.setAccount(account); contact.setAccount(account);
contacts.put(contact.getJid().toBareJid(), contact); contacts.put(contact.getJid().asBareJid(), contact);
return contact; return contact;
} }
return contacts.get(jid.toBareJid()); return contacts.get(jid.asBareJid());
} }
} }
@ -78,7 +79,7 @@ public class Roster {
contact.setAccount(account); contact.setAccount(account);
contact.setOption(Contact.Options.IN_ROSTER); contact.setOption(Contact.Options.IN_ROSTER);
synchronized (this.contacts) { synchronized (this.contacts) {
contacts.put(contact.getJid().toBareJid(), contact); contacts.put(contact.getJid().asBareJid(), contact);
} }
} }

View File

@ -31,9 +31,9 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class IqGenerator extends AbstractGenerator { public class IqGenerator extends AbstractGenerator {
@ -284,7 +284,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) { public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET); final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
final Element block = iq.addChild("block", Namespace.BLOCKING); final Element block = iq.addChild("block", Namespace.BLOCKING);
final Element item = block.addChild("item").setAttribute("jid", jid.toBareJid().toString()); final Element item = block.addChild("item").setAttribute("jid", jid.asBareJid().toString());
if (reportSpam) { if (reportSpam) {
item.addChild("report", "urn:xmpp:reporting:0").addChild("spam"); item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
} }
@ -295,7 +295,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket generateSetUnblockRequest(final Jid jid) { public IqPacket generateSetUnblockRequest(final Jid jid) {
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET); final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
final Element block = iq.addChild("unblock", Namespace.BLOCKING); final Element block = iq.addChild("unblock", Namespace.BLOCKING);
block.addChild("item").setAttribute("jid", jid.toBareJid().toString()); block.addChild("item").setAttribute("jid", jid.asBareJid().toString());
return iq; return iq;
} }
@ -304,7 +304,7 @@ public class IqGenerator extends AbstractGenerator {
packet.setTo(account.getServer()); packet.setTo(account.getServer());
final Element query = packet.addChild("query", Namespace.REGISTER); final Element query = packet.addChild("query", Namespace.REGISTER);
final Jid jid = account.getJid(); final Jid jid = account.getJid();
query.addChild("username").setContent(jid.getLocalpart()); query.addChild("username").setContent(jid.getLocal());
query.addChild("password").setContent(newPassword); query.addChild("password").setContent(newPassword);
return packet; return packet;
} }
@ -317,7 +317,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) { public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
IqPacket packet = new IqPacket(IqPacket.TYPE.SET); IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
packet.setTo(conference.getJid().toBareJid()); packet.setTo(conference.getJid().asBareJid());
packet.setFrom(conference.getAccount().getJid()); packet.setFrom(conference.getAccount().getJid());
Element query = packet.query("http://jabber.org/protocol/muc#admin"); Element query = packet.query("http://jabber.org/protocol/muc#admin");
for(Jid jid : jids) { for(Jid jid : jids) {
@ -330,7 +330,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket changeRole(Conversation conference, String nick, String role) { public IqPacket changeRole(Conversation conference, String nick, String role) {
IqPacket packet = new IqPacket(IqPacket.TYPE.SET); IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
packet.setTo(conference.getJid().toBareJid()); packet.setTo(conference.getJid().asBareJid());
packet.setFrom(conference.getAccount().getJid()); packet.setFrom(conference.getAccount().getJid());
Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item"); Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
item.setAttribute("nick", nick); item.setAttribute("nick", nick);
@ -367,7 +367,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) { public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
final IqPacket register = new IqPacket(IqPacket.TYPE.SET); final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
register.setFrom(account.getJid().toBareJid()); register.setFrom(account.getJid().asBareJid());
register.setTo(account.getServer()); register.setTo(account.getServer());
register.setId(id); register.setId(id);
Element query = register.query("jabber:iq:register"); Element query = register.query("jabber:iq:register");
@ -406,7 +406,7 @@ public class IqGenerator extends AbstractGenerator {
public IqPacket queryAffiliation(Conversation conversation, String affiliation) { public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
IqPacket packet = new IqPacket(IqPacket.TYPE.GET); IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
packet.setTo(conversation.getJid().toBareJid()); packet.setTo(conversation.getJid().asBareJid());
packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation",affiliation); packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation",affiliation);
return packet; return packet;
} }

View File

@ -17,8 +17,8 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import rocks.xmpp.addr.Jid;
public class MessageGenerator extends AbstractGenerator { public class MessageGenerator extends AbstractGenerator {
private static final String OMEMO_FALLBACK_MESSAGE = "I sent you an OMEMO encrypted message but your client doesnt seem to support that. Find more information on https://conversations.im/omemo"; private static final String OMEMO_FALLBACK_MESSAGE = "I sent you an OMEMO encrypted message but your client doesnt seem to support that. Find more information on https://conversations.im/omemo";
@ -47,7 +47,7 @@ public class MessageGenerator extends AbstractGenerator {
packet.addChild("request", "urn:xmpp:receipts"); packet.addChild("request", "urn:xmpp:receipts");
} }
} else { } else {
packet.setTo(message.getCounterpart().toBareJid()); packet.setTo(message.getCounterpart().asBareJid());
packet.setType(MessagePacket.TYPE_GROUPCHAT); packet.setType(MessagePacket.TYPE_GROUPCHAT);
} }
if (conversation.isSingleOrPrivateAndNonAnonymous() && message.getType() != Message.TYPE_PRIVATE) { if (conversation.isSingleOrPrivateAndNonAnonymous() && message.getType() != Message.TYPE_PRIVATE) {
@ -147,7 +147,7 @@ public class MessageGenerator extends AbstractGenerator {
final Account account = conversation.getAccount(); final Account account = conversation.getAccount();
MessagePacket packet = new MessagePacket(); MessagePacket packet = new MessagePacket();
packet.setType(conversation.getMode() == Conversation.MODE_MULTI ? MessagePacket.TYPE_GROUPCHAT : MessagePacket.TYPE_CHAT); packet.setType(conversation.getMode() == Conversation.MODE_MULTI ? MessagePacket.TYPE_GROUPCHAT : MessagePacket.TYPE_CHAT);
packet.setTo(conversation.getJid().toBareJid()); packet.setTo(conversation.getJid().asBareJid());
packet.setFrom(account.getJid()); packet.setFrom(account.getJid());
packet.addChild(ChatState.toElement(conversation.getOutgoingChatState())); packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
packet.addChild("no-store", "urn:xmpp:hints"); packet.addChild("no-store", "urn:xmpp:hints");
@ -158,12 +158,12 @@ public class MessageGenerator extends AbstractGenerator {
public MessagePacket confirm(final Account account, final Jid to, final String id, final Jid counterpart, final boolean groupChat) { public MessagePacket confirm(final Account account, final Jid to, final String id, final Jid counterpart, final boolean groupChat) {
MessagePacket packet = new MessagePacket(); MessagePacket packet = new MessagePacket();
packet.setType(groupChat ? MessagePacket.TYPE_GROUPCHAT : MessagePacket.TYPE_CHAT); packet.setType(groupChat ? MessagePacket.TYPE_GROUPCHAT : MessagePacket.TYPE_CHAT);
packet.setTo(groupChat ? to.toBareJid() : to); packet.setTo(groupChat ? to.asBareJid() : to);
packet.setFrom(account.getJid()); packet.setFrom(account.getJid());
Element displayed = packet.addChild("displayed","urn:xmpp:chat-markers:0"); Element displayed = packet.addChild("displayed","urn:xmpp:chat-markers:0");
displayed.setAttribute("id", id); displayed.setAttribute("id", id);
if (groupChat && counterpart != null) { if (groupChat && counterpart != null) {
displayed.setAttribute("sender",counterpart.toPreppedString()); displayed.setAttribute("sender",counterpart.toString());
} }
packet.addChild("store", "urn:xmpp:hints"); packet.addChild("store", "urn:xmpp:hints");
return packet; return packet;
@ -172,11 +172,11 @@ public class MessageGenerator extends AbstractGenerator {
public MessagePacket conferenceSubject(Conversation conversation,String subject) { public MessagePacket conferenceSubject(Conversation conversation,String subject) {
MessagePacket packet = new MessagePacket(); MessagePacket packet = new MessagePacket();
packet.setType(MessagePacket.TYPE_GROUPCHAT); packet.setType(MessagePacket.TYPE_GROUPCHAT);
packet.setTo(conversation.getJid().toBareJid()); packet.setTo(conversation.getJid().asBareJid());
Element subjectChild = new Element("subject"); Element subjectChild = new Element("subject");
subjectChild.setContent(subject); subjectChild.setContent(subject);
packet.addChild(subjectChild); packet.addChild(subjectChild);
packet.setFrom(conversation.getAccount().getJid().toBareJid()); packet.setFrom(conversation.getAccount().getJid().asBareJid());
return packet; return packet;
} }
@ -186,7 +186,7 @@ public class MessageGenerator extends AbstractGenerator {
packet.setTo(contact); packet.setTo(contact);
packet.setFrom(conversation.getAccount().getJid()); packet.setFrom(conversation.getAccount().getJid());
Element x = packet.addChild("x", "jabber:x:conference"); Element x = packet.addChild("x", "jabber:x:conference");
x.setAttribute("jid", conversation.getJid().toBareJid().toString()); x.setAttribute("jid", conversation.getJid().asBareJid().toString());
String password = conversation.getMucOptions().getPassword(); String password = conversation.getMucOptions().getPassword();
if (password != null) { if (password != null) {
x.setAttribute("password",password); x.setAttribute("password",password);
@ -196,12 +196,12 @@ public class MessageGenerator extends AbstractGenerator {
public MessagePacket invite(Conversation conversation, Jid contact) { public MessagePacket invite(Conversation conversation, Jid contact) {
MessagePacket packet = new MessagePacket(); MessagePacket packet = new MessagePacket();
packet.setTo(conversation.getJid().toBareJid()); packet.setTo(conversation.getJid().asBareJid());
packet.setFrom(conversation.getAccount().getJid()); packet.setFrom(conversation.getAccount().getJid());
Element x = new Element("x"); Element x = new Element("x");
x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user"); x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
Element invite = new Element("invite"); Element invite = new Element("invite");
invite.setAttribute("to", contact.toBareJid().toString()); invite.setAttribute("to", contact.asBareJid().toString());
x.addChild(invite); x.addChild(invite);
packet.addChild(x); packet.addChild(x);
return packet; return packet;

View File

@ -18,7 +18,7 @@ public class PresenceGenerator extends AbstractGenerator {
PresencePacket packet = new PresencePacket(); PresencePacket packet = new PresencePacket();
packet.setAttribute("type", type); packet.setAttribute("type", type);
packet.setTo(contact.getJid()); packet.setTo(contact.getJid());
packet.setFrom(contact.getAccount().getJid().toBareJid()); packet.setFrom(contact.getAccount().getJid().asBareJid());
return packet; return packet;
} }

View File

@ -29,8 +29,8 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class HttpUploadConnection implements Transferable { public class HttpUploadConnection implements Transferable {
@ -121,7 +121,7 @@ public class HttpUploadConnection implements Transferable {
try { try {
pair = AbstractConnectionManager.createInputStream(file, true); pair = AbstractConnectionManager.createInputStream(file, true);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid()+": could not find file to upload - "+e.getMessage()); Log.d(Config.LOGTAG, account.getJid().asBareJid()+": could not find file to upload - "+e.getMessage());
fail(e.getMessage()); fail(e.getMessage());
return; return;
} }
@ -220,7 +220,7 @@ public class HttpUploadConnection implements Transferable {
mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl); mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
mXmppConnectionService.getFileBackend().updateMediaScanner(file); mXmppConnectionService.getFileBackend().updateMediaScanner(file);
message.setTransferable(null); message.setTransferable(null);
message.setCounterpart(message.getConversation().getJid().toBareJid()); message.setCounterpart(message.getConversation().getJid().asBareJid());
mXmppConnectionService.resendMessage(message, delayed); mXmppConnectionService.resendMessage(message, delayed);
} else { } else {
Log.d(Config.LOGTAG,"http upload failed because response code was "+code); Log.d(Config.LOGTAG,"http upload failed because response code was "+code);

View File

@ -11,9 +11,8 @@ import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.MucOptions; import eu.siacs.conversations.entities.MucOptions;
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.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.AbstractStanza; import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
import rocks.xmpp.addr.Jid;
public abstract class AbstractParser { public abstract class AbstractParser {
@ -39,7 +38,7 @@ public abstract class AbstractParser {
for(Element child : element.getChildren()) { for(Element child : element.getChildren()) {
if ("delay".equals(child.getName()) && "urn:xmpp:delay".equals(child.getNamespace())) { if ("delay".equals(child.getName()) && "urn:xmpp:delay".equals(child.getNamespace())) {
final Jid f = to == null ? null : child.getAttributeAsJid("from"); final Jid f = to == null ? null : child.getAttributeAsJid("from");
if (f != null && (to.toBareJid().equals(f) || to.getDomainpart().equals(f.toString()))) { if (f != null && (to.asBareJid().equals(f) || to.getDomain().equals(f.toString()))) {
continue; continue;
} }
final String stamp = child.getAttribute("stamp"); final String stamp = child.getAttribute("stamp");
@ -86,7 +85,7 @@ public abstract class AbstractParser {
protected void updateLastseen(final Account account, final Jid from) { protected void updateLastseen(final Account account, final Jid from) {
final Contact contact = account.getRoster().getContact(from); final Contact contact = account.getRoster().getContact(from);
contact.setLastResource(from.isBareJid() ? "" : from.getResourcepart()); contact.setLastResource(from.isBareJid() ? "" : from.getResource());
} }
protected String avatarData(Element items) { protected String avatarData(Element items) {
@ -102,15 +101,15 @@ public abstract class AbstractParser {
} }
public static MucOptions.User parseItem(Conversation conference, Element item, Jid fullJid) { public static MucOptions.User parseItem(Conversation conference, Element item, Jid fullJid) {
final String local = conference.getJid().getLocalpart(); final String local = conference.getJid().getLocal();
final String domain = conference.getJid().getDomainpart(); final String domain = conference.getJid().getDomain();
String affiliation = item.getAttribute("affiliation"); String affiliation = item.getAttribute("affiliation");
String role = item.getAttribute("role"); String role = item.getAttribute("role");
String nick = item.getAttribute("nick"); String nick = item.getAttribute("nick");
if (nick != null && fullJid == null) { if (nick != null && fullJid == null) {
try { try {
fullJid = Jid.fromParts(local, domain, nick); fullJid = Jid.of(local, domain, nick);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
fullJid = null; fullJid = null;
} }
} }

View File

@ -31,8 +31,8 @@ import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class IqParser extends AbstractParser implements OnIqPacketReceived { public class IqParser extends AbstractParser implements OnIqPacketReceived {
@ -70,7 +70,7 @@ public class IqParser extends AbstractParser implements OnIqPacketReceived {
} }
boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM); boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
if ((both != bothPre) && both) { if ((both != bothPre) && both) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": gained mutual presence subscription with "+contact.getJid()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": gained mutual presence subscription with "+contact.getJid());
AxolotlService axolotlService = account.getAxolotlService(); AxolotlService axolotlService = account.getAxolotlService();
if (axolotlService != null) { if (axolotlService != null) {
axolotlService.clearErrorsInFetchStatusMap(contact.getJid()); axolotlService.clearErrorsInFetchStatusMap(contact.getJid());

View File

@ -32,9 +32,9 @@ import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnMessagePacketReceived; import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import rocks.xmpp.addr.Jid;
public class MessageParser extends AbstractParser implements OnMessagePacketReceived { public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
@ -47,7 +47,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if (state != null && c != null) { if (state != null && c != null) {
final Account account = c.getAccount(); final Account account = c.getAccount();
Jid from = packet.getFrom(); Jid from = packet.getFrom();
if (from.toBareJid().equals(account.getJid().toBareJid())) { if (from.asBareJid().equals(account.getJid().asBareJid())) {
c.setOutgoingChatState(state); c.setOutgoingChatState(state);
if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) { if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
mXmppConnectionService.markRead(c); mXmppConnectionService.markRead(c);
@ -74,9 +74,9 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
final AxolotlService service = conversation.getAccount().getAxolotlService(); final AxolotlService service = conversation.getAccount().getAxolotlService();
final XmppAxolotlMessage xmppAxolotlMessage; final XmppAxolotlMessage xmppAxolotlMessage;
try { try {
xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid()); xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": invalid omemo message received " + e.getMessage()); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
return null; return null;
} }
if (xmppAxolotlMessage.hasPayload()) { if (xmppAxolotlMessage.hasPayload()) {
@ -88,7 +88,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
return finishedMessage; return finishedMessage;
} }
} else { } else {
Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": received OMEMO key transport message"); Log.d(Config.LOGTAG,conversation.getAccount().getJid().asBareJid()+": received OMEMO key transport message");
service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone); service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
} }
return null; return null;
@ -145,11 +145,11 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
final Jid by; final Jid by;
final boolean safeToExtract; final boolean safeToExtract;
if (isTypeGroupChat) { if (isTypeGroupChat) {
by = conversation.getJid().toBareJid(); by = conversation.getJid().asBareJid();
safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS); safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
} else { } else {
Account account = conversation.getAccount(); Account account = conversation.getAccount();
by = account.getJid().toBareJid(); by = account.getJid().asBareJid();
safeToExtract = account.getXmppConnection().getFeatures().stanzaIds(); safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
} }
return safeToExtract ? extractStanzaId(packet, by) : null; return safeToExtract ? extractStanzaId(packet, by) : null;
@ -172,9 +172,9 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if ("urn:xmpp:avatar:metadata".equals(node)) { if ("urn:xmpp:avatar:metadata".equals(node)) {
Avatar avatar = Avatar.parseMetadata(items); Avatar avatar = Avatar.parseMetadata(items);
if (avatar != null) { if (avatar != null) {
avatar.owner = from.toBareJid(); avatar.owner = from.asBareJid();
if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) { if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
if (account.getJid().toBareJid().equals(from)) { if (account.getJid().asBareJid().equals(from)) {
if (account.setAvatar(avatar.getFilename())) { if (account.setAvatar(avatar.getFilename())) {
mXmppConnectionService.databaseBackend.updateAccount(account); mXmppConnectionService.databaseBackend.updateAccount(account);
} }
@ -218,7 +218,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
Jid from = packet.getFrom(); Jid from = packet.getFrom();
if (from != null) { if (from != null) {
Message message = mXmppConnectionService.markMessage(account, Message message = mXmppConnectionService.markMessage(account,
from.toBareJid(), from.asBareJid(),
packet.getId(), packet.getId(),
Message.STATUS_SEND_FAILED, Message.STATUS_SEND_FAILED,
extractErrorMessage(packet)); extractErrorMessage(packet));
@ -257,7 +257,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
serverMsgId = result.getAttribute("id"); serverMsgId = result.getAttribute("id");
query.incrementMessageCount(); query.incrementMessageCount();
} else if (query != null) { } else if (query != null) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received mam result from invalid sender"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result from invalid sender");
return; return;
} else if (original.fromServer(account)) { } else if (original.fromServer(account)) {
Pair<MessagePacket, Long> f; Pair<MessagePacket, Long> f;
@ -306,7 +306,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT; boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
if (query != null && !query.muc() && isTypeGroupChat) { if (query != null && !query.muc() && isTypeGroupChat) {
Log.e(Config.LOGTAG,account.getJid().toBareJid()+": received groupchat ("+from+") message on regular MAM request. skipping"); Log.e(Config.LOGTAG,account.getJid().asBareJid()+": received groupchat ("+from+") message on regular MAM request. skipping");
return; return;
} }
boolean isProperlyAddressed = (to != null) && (!to.isBareJid() || account.countPresences() == 0); boolean isProperlyAddressed = (to != null) && (!to.isBareJid() || account.countPresences() == 0);
@ -314,7 +314,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
boolean selfAddressed; boolean selfAddressed;
if (packet.fromAccount(account)) { if (packet.fromAccount(account)) {
status = Message.STATUS_SEND; status = Message.STATUS_SEND;
selfAddressed = to == null || account.getJid().toBareJid().equals(to.toBareJid()); selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
if (selfAddressed) { if (selfAddressed) {
counterpart = from; counterpart = from;
} else { } else {
@ -332,7 +332,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) { if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query, false); final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), isTypeGroupChat, false, query, false);
final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI; final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
if (serverMsgId == null) { if (serverMsgId == null) {
@ -384,7 +384,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, query != null); message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, query != null);
if (message == null) { if (message == null) {
if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) { if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
} }
if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) { if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
@ -392,7 +392,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) { if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
previouslySent.setServerMsgId(serverMsgId); previouslySent.setServerMsgId(serverMsgId);
mXmppConnectionService.databaseBackend.updateMessage(previouslySent); mXmppConnectionService.databaseBackend.updateMessage(previouslySent);
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": encountered previously sent OMEMO message without serverId. updating..."); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": encountered previously sent OMEMO message without serverId. updating...");
} }
} }
return; return;
@ -432,7 +432,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} else { } else {
trueCounterpart = fallback; trueCounterpart = fallback;
} }
if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) { if (trueCounterpart != null && trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND; status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
} }
message.setStatus(status); message.setStatus(status);
@ -470,7 +470,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) { if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
replacedMessage.markUnread(); replacedMessage.markUnread();
} }
extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet); extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
mXmppConnectionService.updateMessage(replacedMessage, uuid); mXmppConnectionService.updateMessage(replacedMessage, uuid);
mXmppConnectionService.getNotificationService().updateNotification(false); mXmppConnectionService.getNotificationService().updateNotification(false);
if (mXmppConnectionService.confirmMessages() if (mXmppConnectionService.confirmMessages()
@ -488,14 +488,14 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
return; return;
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received message correction but verification didn't check out"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
} }
} }
} }
long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate(); long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
if (deletionDate != 0 && message.getTimeSent() < deletionDate) { if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
return; return;
} }
@ -547,7 +547,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
if (query == null) { if (query == null) {
extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet); extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
} }
@ -573,7 +573,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
} else if (!packet.hasChild("body")) { //no body } else if (!packet.hasChild("body")) { //no body
final Conversation conversation = mXmppConnectionService.find(account, from.toBareJid()); final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
if (axolotlEncrypted != null) { if (axolotlEncrypted != null) {
Jid origin; Jid origin;
if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) { if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
@ -589,16 +589,16 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
origin = from; origin = from;
} }
try { try {
final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.toBareJid()); final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null); account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": omemo key transport message received from "+origin); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": omemo key transport message received from "+origin);
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": invalid omemo key transport message received " + e.getMessage()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
return; return;
} }
} }
if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) { if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateConversationUi();
} }
@ -637,7 +637,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
MucOptions.User user = AbstractParser.parseItem(conversation, child); MucOptions.User user = AbstractParser.parseItem(conversation, child);
Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for " Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
+ user.getRealJid() + " to " + user.getAffiliation() + " in " + user.getRealJid() + " to " + user.getAffiliation() + " in "
+ conversation.getJid().toBareJid()); + conversation.getJid().asBareJid());
if (!user.realJidMatchesAccount()) { if (!user.realJidMatchesAccount()) {
boolean isNew = conversation.getMucOptions().updateUser(user); boolean isNew = conversation.getMucOptions().updateUser(user);
mXmppConnectionService.getAvatarService().clear(conversation); mXmppConnectionService.getAvatarService().clear(conversation);
@ -648,7 +648,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
Jid jid = user.getRealJid(); Jid jid = user.getRealJid();
List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets(); List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
if (cryptoTargets.remove(user.getRealJid())) { if (cryptoTargets.remove(user.getRealJid())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
conversation.setAcceptedCryptoTargets(cryptoTargets); conversation.setAcceptedCryptoTargets(cryptoTargets);
mXmppConnectionService.updateConversation(conversation); mXmppConnectionService.updateConversation(conversation);
} }
@ -676,7 +676,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
query.pendingReceiptRequests.remove(new ReceiptRequest(packet.getTo(),id)); query.pendingReceiptRequests.remove(new ReceiptRequest(packet.getTo(),id));
} }
} else { } else {
mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED); mXmppConnectionService.markMessage(account, from.asBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
} }
} }
Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0"); Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
@ -686,13 +686,13 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if (packet.fromAccount(account) && !selfAddressed) { if (packet.fromAccount(account) && !selfAddressed) {
dismissNotification(account, counterpart, query); dismissNotification(account, counterpart, query);
} else if (isTypeGroupChat) { } else if (isTypeGroupChat) {
Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid()); Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
if (conversation != null && id != null && sender != null) { if (conversation != null && id != null && sender != null) {
Message message = conversation.findMessageWithRemoteId(id, sender); Message message = conversation.findMessageWithRemoteId(id, sender);
if (message != null) { if (message != null) {
final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart); final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback); final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
final boolean trueJidMatchesAccount = account.getJid().toBareJid().equals(trueJid == null ? null : trueJid.toBareJid()); final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) { if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
mXmppConnectionService.markRead(conversation); mXmppConnectionService.markRead(conversation);
@ -700,14 +700,14 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} else if (!counterpart.isBareJid() && trueJid != null){ } else if (!counterpart.isBareJid() && trueJid != null){
ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid); ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
if (message.addReadByMarker(readByMarker)) { if (message.addReadByMarker(readByMarker)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": added read by (" + readByMarker.getRealJid() + ") to message '" + message.getBody() + "'"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": added read by (" + readByMarker.getRealJid() + ") to message '" + message.getBody() + "'");
mXmppConnectionService.updateMessage(message); mXmppConnectionService.updateMessage(message);
} }
} }
} }
} }
} else { } else {
final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), id, Message.STATUS_SEND_DISPLAYED); final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
Message message = displayedMessage == null ? null : displayedMessage.prev(); Message message = displayedMessage == null ? null : displayedMessage.prev();
while (message != null while (message != null
&& message.getStatus() == Message.STATUS_SEND_RECEIVED && message.getStatus() == Message.STATUS_SEND_RECEIVED
@ -736,7 +736,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query) { private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query) {
Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid()); Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
if (conversation != null && (query == null || query.isCatchup())) { if (conversation != null && (query == null || query.isCatchup())) {
mXmppConnectionService.markRead(conversation); //TODO only mark messages read that are older than timestamp mXmppConnectionService.markRead(conversation); //TODO only mark messages read that are older than timestamp
} }
@ -777,7 +777,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
private void activateGracePeriod(Account account) { private void activateGracePeriod(Account account) {
long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000; long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration))); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
account.activateGracePeriod(duration); account.activateGracePeriod(duration);
} }
} }

View File

@ -23,9 +23,9 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.OnPresencePacketReceived; import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket; import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
import rocks.xmpp.addr.Jid;
public class PresenceParser extends AbstractParser implements public class PresenceParser extends AbstractParser implements
OnPresencePacketReceived { OnPresencePacketReceived {
@ -35,7 +35,7 @@ public class PresenceParser extends AbstractParser implements
} }
public void parseConferencePresence(PresencePacket packet, Account account) { public void parseConferencePresence(PresencePacket packet, Account account) {
final Conversation conversation = packet.getFrom() == null ? null : mXmppConnectionService.find(account, packet.getFrom().toBareJid()); final Conversation conversation = packet.getFrom() == null ? null : mXmppConnectionService.find(account, packet.getFrom().asBareJid());
if (conversation != null) { if (conversation != null) {
final MucOptions mucOptions = conversation.getMucOptions(); final MucOptions mucOptions = conversation.getMucOptions();
boolean before = mucOptions.online(); boolean before = mucOptions.online();
@ -89,9 +89,9 @@ public class PresenceParser extends AbstractParser implements
axolotlService.fetchDeviceIds(user.getRealJid()); axolotlService.fetchDeviceIds(user.getRealJid());
} }
if (codes.contains(MucOptions.STATUS_CODE_ROOM_CREATED) && mucOptions.autoPushConfiguration()) { if (codes.contains(MucOptions.STATUS_CODE_ROOM_CREATED) && mucOptions.autoPushConfiguration()) {
Log.d(Config.LOGTAG,mucOptions.getAccount().getJid().toBareJid() Log.d(Config.LOGTAG,mucOptions.getAccount().getJid().asBareJid()
+": room '" +": room '"
+mucOptions.getConversation().getJid().toBareJid() +mucOptions.getConversation().getJid().asBareJid()
+"' created. pushing default configuration"); +"' created. pushing default configuration");
mXmppConnectionService.pushConferenceConfiguration(mucOptions.getConversation(), mXmppConnectionService.pushConferenceConfiguration(mucOptions.getConversation(),
IqGenerator.defaultRoomConfiguration(), IqGenerator.defaultRoomConfiguration(),
@ -217,15 +217,15 @@ public class PresenceParser extends AbstractParser implements
final String type = packet.getAttribute("type"); final String type = packet.getAttribute("type");
final Contact contact = account.getRoster().getContact(from); final Contact contact = account.getRoster().getContact(from);
if (type == null) { if (type == null) {
final String resource = from.isBareJid() ? "" : from.getResourcepart(); final String resource = from.isBareJid() ? "" : from.getResource();
if (contact.setPresenceName(packet.findChildContent("nick", Namespace.NICK))) { if (contact.setPresenceName(packet.findChildContent("nick", Namespace.NICK))) {
mXmppConnectionService.getAvatarService().clear(contact); mXmppConnectionService.getAvatarService().clear(contact);
} }
Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update")); Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
if (avatar != null && (!contact.isSelf() || account.getAvatar() == null)) { if (avatar != null && (!contact.isSelf() || account.getAvatar() == null)) {
avatar.owner = from.toBareJid(); avatar.owner = from.asBareJid();
if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) { if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
if (avatar.owner.equals(account.getJid().toBareJid())) { if (avatar.owner.equals(account.getJid().asBareJid())) {
account.setAvatar(avatar.getFilename()); account.setAvatar(avatar.getFilename());
mXmppConnectionService.databaseBackend.updateAccount(account); mXmppConnectionService.databaseBackend.updateAccount(account);
mXmppConnectionService.getAvatarService().clear(account); mXmppConnectionService.getAvatarService().clear(account);
@ -284,7 +284,7 @@ public class PresenceParser extends AbstractParser implements
if (from.isBareJid()) { if (from.isBareJid()) {
contact.clearPresences(); contact.clearPresences();
} else { } else {
contact.removePresence(from.getResourcepart()); contact.removePresence(from.getResource());
} }
mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, false); mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, false);
} else if (type.equals("subscribe")) { } else if (type.equals("subscribe")) {
@ -294,7 +294,7 @@ public class PresenceParser extends AbstractParser implements
} else { } else {
contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST); contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
final Conversation conversation = mXmppConnectionService.findOrCreateConversation( final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
account, contact.getJid().toBareJid(), false, false); account, contact.getJid().asBareJid(), false, false);
final String statusMessage = packet.findChildContent("status"); final String statusMessage = packet.findChildContent("status");
if (statusMessage != null if (statusMessage != null
&& !statusMessage.isEmpty() && !statusMessage.isEmpty()

View File

@ -4,7 +4,6 @@ import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.database.DatabaseUtils; import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteCantOpenDatabaseException;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment; import android.os.Environment;
@ -28,7 +27,6 @@ import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -53,9 +51,8 @@ import eu.siacs.conversations.services.ShortcutService;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.utils.MimeUtils;
import eu.siacs.conversations.utils.Resolver; import eu.siacs.conversations.utils.Resolver;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.mam.MamReference; import eu.siacs.conversations.xmpp.mam.MamReference;
import rocks.xmpp.addr.Jid;
public class DatabaseBackend extends SQLiteOpenHelper { public class DatabaseBackend extends SQLiteOpenHelper {
@ -320,7 +317,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
continue; continue;
} }
int ownDeviceId = Integer.valueOf(ownDeviceIdString); int ownDeviceId = Integer.valueOf(ownDeviceIdString);
SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().toBareJid().toPreppedString(), ownDeviceId); SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownDeviceId);
deleteSession(db, account, ownAddress); deleteSession(db, account, ownAddress);
IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account); IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
if (identityKeyPair != null) { if (identityKeyPair != null) {
@ -335,7 +332,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
+ SQLiteAxolotlStore.FINGERPRINT + " = ? ", + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
selectionArgs); selectionArgs);
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not load own identity key pair"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not load own identity key pair");
} }
} }
} }
@ -497,10 +494,8 @@ public class DatabaseBackend extends SQLiteOpenHelper {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
String newJid; String newJid;
try { try {
newJid = Jid.fromString( newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID)) } catch (IllegalArgumentException ignored) {
).toPreppedString();
} catch (InvalidJidException ignored) {
Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID " Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
+ cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID)) + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
+ ": " + ignored + ". Skipping..."); + ": " + ignored + ". Skipping...");
@ -522,10 +517,8 @@ public class DatabaseBackend extends SQLiteOpenHelper {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
String newJid; String newJid;
try { try {
newJid = Jid.fromString( newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
cursor.getString(cursor.getColumnIndex(Contact.JID)) } catch (IllegalArgumentException ignored) {
).toPreppedString();
} catch (InvalidJidException ignored) {
Log.e(Config.LOGTAG, "Failed to migrate Contact JID " Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
+ cursor.getString(cursor.getColumnIndex(Contact.JID)) + cursor.getString(cursor.getColumnIndex(Contact.JID))
+ ": " + ignored + ". Skipping..."); + ": " + ignored + ". Skipping...");
@ -549,12 +542,12 @@ public class DatabaseBackend extends SQLiteOpenHelper {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
String newServer; String newServer;
try { try {
newServer = Jid.fromParts( newServer = Jid.of(
cursor.getString(cursor.getColumnIndex(Account.USERNAME)), cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
cursor.getString(cursor.getColumnIndex(Account.SERVER)), cursor.getString(cursor.getColumnIndex(Account.SERVER)),
"mobile" null
).getDomainpart(); ).getDomain();
} catch (InvalidJidException ignored) { } catch (IllegalArgumentException ignored) {
Log.e(Config.LOGTAG, "Failed to migrate Account SERVER " Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
+ cursor.getString(cursor.getColumnIndex(Account.SERVER)) + cursor.getString(cursor.getColumnIndex(Account.SERVER))
+ ": " + ignored + ". Skipping..."); + ": " + ignored + ". Skipping...");
@ -751,8 +744,8 @@ public class DatabaseBackend extends SQLiteOpenHelper {
public Conversation findConversation(final Account account, final Jid contactJid) { public Conversation findConversation(final Account account, final Jid contactJid) {
SQLiteDatabase db = this.getReadableDatabase(); SQLiteDatabase db = this.getReadableDatabase();
String[] selectionArgs = {account.getUuid(), String[] selectionArgs = {account.getUuid(),
contactJid.toBareJid().toPreppedString() + "/%", contactJid.asBareJid().toString() + "/%",
contactJid.toBareJid().toPreppedString() contactJid.asBareJid().toString()
}; };
Cursor cursor = db.query(Conversation.TABLENAME, null, Cursor cursor = db.query(Conversation.TABLENAME, null,
Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
@ -786,7 +779,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
Cursor cursor = db.query(Account.TABLENAME,columns,null,null,null,null,null); Cursor cursor = db.query(Account.TABLENAME,columns,null,null,null,null,null);
try { try {
while(cursor.moveToNext()) { while(cursor.moveToNext()) {
jids.add(Jid.fromParts(cursor.getString(0),cursor.getString(1),null)); jids.add(Jid.of(cursor.getString(0),cursor.getString(1),null));
} }
return jids; return jids;
} catch (Exception e) { } catch (Exception e) {
@ -864,7 +857,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
db.insert(Contact.TABLENAME, null, contact.getContentValues()); db.insert(Contact.TABLENAME, null, contact.getContentValues());
} else { } else {
String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?"; String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
String[] whereArgs = {account.getUuid(), contact.getJid().toPreppedString()}; String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
db.delete(Contact.TABLENAME, where, whereArgs); db.delete(Contact.TABLENAME, where, whereArgs);
} }
} }
@ -1257,7 +1250,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
} }
private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) { private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
String name = account.getJid().toBareJid().toPreppedString(); String name = account.getJid().asBareJid().toString();
IdentityKeyPair identityKeyPair = null; IdentityKeyPair identityKeyPair = null;
Cursor cursor = getIdentityKeyCursor(db, account, name, true); Cursor cursor = getIdentityKeyCursor(db, account, name, true);
if (cursor.getCount() != 0) { if (cursor.getCount() != 0) {
@ -1265,7 +1258,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
try { try {
identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)); identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
} }
} }
cursor.close(); cursor.close();
@ -1290,10 +1283,10 @@ public class DatabaseBackend extends SQLiteOpenHelper {
if (key != null) { if (key != null) {
identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0)); identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
} else { } else {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().toBareJid() + ", address: " + name); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
} }
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
} }
} }
cursor.close(); cursor.close();
@ -1429,7 +1422,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
} }
public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) { public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
storeIdentityKey(account, account.getJid().toBareJid().toPreppedString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false)); storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
} }
@ -1474,7 +1467,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>(); ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
while(cursor.moveToNext()) { while(cursor.moveToNext()) {
try { try {
contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.fromString(cursor.getString(1)))); contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG,e.getMessage()); Log.d(Config.LOGTAG,e.getMessage());
} }

View File

@ -30,7 +30,7 @@ import eu.siacs.conversations.entities.MucOptions;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded; import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class AvatarService implements OnAdvancedStreamFeaturesLoaded { public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
@ -68,7 +68,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
avatar = mXmppConnectionService.getFileBackend().getAvatar(contact.getAvatar(), size); avatar = mXmppConnectionService.getFileBackend().getAvatar(contact.getAvatar(), size);
} }
if (avatar == null) { if (avatar == null) {
avatar = get(contact.getDisplayName(), contact.getJid().toBareJid().toString(), size, cachedOnly); avatar = get(contact.getDisplayName(), contact.getJid().asBareJid().toString(), size, cachedOnly);
} }
this.mXmppConnectionService.getBitmapCache().put(KEY, avatar); this.mXmppConnectionService.getBitmapCache().put(KEY, avatar);
return avatar; return avatar;
@ -115,7 +115,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
if (contact != null) { if (contact != null) {
avatar = get(contact, size, cachedOnly); avatar = get(contact, size, cachedOnly);
} else { } else {
String seed = user.getRealJid() != null ? user.getRealJid().toBareJid().toString() : null; String seed = user.getRealJid() != null ? user.getRealJid().asBareJid().toString() : null;
avatar = get(user.getName(), seed, size, cachedOnly); avatar = get(user.getName(), seed, size, cachedOnly);
} }
} }
@ -141,7 +141,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
this.sizes.add(size); this.sizes.add(size);
} }
} }
return PREFIX_CONTACT + "_" + contact.getAccount().getJid().toBareJid() + "_" return PREFIX_CONTACT + "_" + contact.getAccount().getJid().asBareJid() + "_"
+ contact.getJid() + "_" + String.valueOf(size); + contact.getJid() + "_" + String.valueOf(size);
} }
@ -151,7 +151,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
this.sizes.add(size); this.sizes.add(size);
} }
} }
return PREFIX_CONTACT + "_" + user.getAccount().getJid().toBareJid() + "_" return PREFIX_CONTACT + "_" + user.getAccount().getJid().asBareJid() + "_"
+ user.getFullJid() + "_" + String.valueOf(size); + user.getFullJid() + "_" + String.valueOf(size);
} }
@ -167,11 +167,11 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
if (bookmark.getConversation() != null) { if (bookmark.getConversation() != null) {
return get(bookmark.getConversation(), size, cachedOnly); return get(bookmark.getConversation(), size, cachedOnly);
} else { } else {
String seed = bookmark.getJid() != null ? bookmark.getJid().toBareJid().toString() : null; String seed = bookmark.getJid() != null ? bookmark.getJid().asBareJid().toString() : null;
return get(bookmark.getDisplayName(), seed, size, cachedOnly); return get(bookmark.getDisplayName(), seed, size, cachedOnly);
} }
} else { } else {
String seed = item.getJid() != null ? item.getJid().toBareJid().toString() : null; String seed = item.getJid() != null ? item.getJid().asBareJid().toString() : null;
return get(item.getDisplayName(), seed, size, cachedOnly); return get(item.getDisplayName(), seed, size, cachedOnly);
} }
} }
@ -216,7 +216,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
final List<MucOptions.User> users = mucOptions.getUsersRelevantForNameAndAvatar(); final List<MucOptions.User> users = mucOptions.getUsersRelevantForNameAndAvatar();
if (users.size() == 0) { if (users.size() == 0) {
Conversation c = mucOptions.getConversation(); Conversation c = mucOptions.getConversation();
bitmap = getImpl(c.getName(),c.getJid().toBareJid().toString(),size); bitmap = getImpl(c.getName(),c.getJid().asBareJid().toString(),size);
} else { } else {
bitmap = getImpl(users,size); bitmap = getImpl(users,size);
} }
@ -294,9 +294,9 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
for(MucOptions.User user : users) { for(MucOptions.User user : users) {
builder.append("\0"); builder.append("\0");
builder.append(user.getRealJid() == null ? "" : user.getRealJid().toBareJid().toPreppedString()); builder.append(user.getRealJid() == null ? "" : user.getRealJid().asBareJid().toString());
builder.append("\0"); builder.append("\0");
builder.append(user.getFullJid() == null ? "" : user.getFullJid().toPreppedString()); builder.append(user.getFullJid() == null ? "" : user.getFullJid().toString());
} }
final String key = builder.toString(); final String key = builder.toString();
synchronized (this.conversationDependentKeys) { synchronized (this.conversationDependentKeys) {
@ -324,7 +324,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
} }
avatar = mXmppConnectionService.getFileBackend().getAvatar(account.getAvatar(), size); avatar = mXmppConnectionService.getFileBackend().getAvatar(account.getAvatar(), size);
if (avatar == null) { if (avatar == null) {
avatar = get(account.getJid().toBareJid().toString(), null, size,false); avatar = get(account.getJid().asBareJid().toString(), null, size,false);
} }
mXmppConnectionService.getBitmapCache().put(KEY, avatar); mXmppConnectionService.getBitmapCache().put(KEY, avatar);
return avatar; return avatar;
@ -353,7 +353,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
return get(c, size, cachedOnly); return get(c, size, cachedOnly);
} }
Jid tcp = message.getTrueCounterpart(); Jid tcp = message.getTrueCounterpart();
String seed = tcp != null ? tcp.toBareJid().toString() :null; String seed = tcp != null ? tcp.asBareJid().toString() :null;
return get(UIHelper.getMessageDisplayName(message), seed, size, cachedOnly); return get(UIHelper.getMessageDisplayName(message), seed, size, cachedOnly);
} else { } else {
return get(conversation.getAccount(), size, cachedOnly); return get(conversation.getAccount(), size, cachedOnly);
@ -458,10 +458,10 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
if (contact != null) { if (contact != null) {
String seed = contact.getJid().toBareJid().toString(); String seed = contact.getJid().asBareJid().toString();
drawTile(canvas, contact.getDisplayName(), seed, left, top, right, bottom); drawTile(canvas, contact.getDisplayName(), seed, left, top, right, bottom);
} else { } else {
String seed = user.getRealJid() == null ? null : user.getRealJid().toBareJid().toString(); String seed = user.getRealJid() == null ? null : user.getRealJid().asBareJid().toString();
drawTile(canvas, user.getName(), seed, left, top, right, bottom); drawTile(canvas, user.getName(), seed, left, top, right, bottom);
} }
return true; return true;
@ -477,7 +477,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
} }
String name = account.getJid().toBareJid().toString(); String name = account.getJid().asBareJid().toString();
return drawTile(canvas, name, name, left, top, right, bottom); return drawTile(canvas, name, name, left, top, right, bottom);
} }
@ -522,7 +522,7 @@ public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
public void onAdvancedStreamFeaturesAvailable(Account account) { public void onAdvancedStreamFeaturesAvailable(Account account) {
XmppConnection.Features features = account.getXmppConnection().getFeatures(); XmppConnection.Features features = account.getXmppConnection().getFeatures();
if (features.pep() && !features.pepPersistent()) { if (features.pep() && !features.pepPersistent()) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": has pep but is not persistent"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": has pep but is not persistent");
if (account.getAvatar() != null) { if (account.getAvatar() != null) {
mXmppConnectionService.republishAvatarIfNeeded(account); mXmppConnectionService.republishAvatarIfNeeded(account);
} }

View File

@ -31,7 +31,7 @@ import java.util.Hashtable;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class BarcodeProvider extends ContentProvider implements ServiceConnection { public class BarcodeProvider extends ContentProvider implements ServiceConnection {
@ -99,7 +99,7 @@ public class BarcodeProvider extends ContentProvider implements ServiceConnectio
if (connectAndWait()) { if (connectAndWait()) {
Log.d(Config.LOGTAG, "connected to background service"); Log.d(Config.LOGTAG, "connected to background service");
try { try {
Account account = mXmppConnectionService.findAccountByJid(Jid.fromString(jid)); Account account = mXmppConnectionService.findAccountByJid(Jid.of(jid));
if (account != null) { if (account != null) {
String shareableUri = account.getShareableUri(); String shareableUri = account.getShareableUri();
String hash = CryptoHelper.getFingerprint(shareableUri); String hash = CryptoHelper.getFingerprint(shareableUri);
@ -179,7 +179,7 @@ public class BarcodeProvider extends ContentProvider implements ServiceConnectio
public static Uri getUriForAccount(Context context, Account account) { public static Uri getUriForAccount(Context context, Account account) {
final String packageId = context.getPackageName(); final String packageId = context.getPackageName();
return Uri.parse("content://" + packageId + AUTHORITY + "/" + account.getJid().toBareJid() + ".png"); return Uri.parse("content://" + packageId + AUTHORITY + "/" + account.getJid().asBareJid() + ".png");
} }
public static Bitmap create2dBarcodeBitmap(String input, int size) { public static Bitmap create2dBarcodeBitmap(String input, int size) {

View File

@ -21,7 +21,7 @@ import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.persistance.DatabaseBackend; import eu.siacs.conversations.persistance.DatabaseBackend;
import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class ExportLogsService extends Service { public class ExportLogsService extends Service {
@ -78,7 +78,7 @@ public class ExportLogsService extends Service {
Jid accountJid = resolveAccountUuid(conversation.getAccountUuid()); Jid accountJid = resolveAccountUuid(conversation.getAccountUuid());
Jid contactJid = conversation.getJid(); Jid contactJid = conversation.getJid();
File dir = new File(String.format(DIRECTORY_STRING_FORMAT,accountJid.toBareJid().toString())); File dir = new File(String.format(DIRECTORY_STRING_FORMAT,accountJid.asBareJid().toString()));
dir.mkdirs(); dir.mkdirs();
BufferedWriter bw = null; BufferedWriter bw = null;
@ -90,7 +90,7 @@ public class ExportLogsService extends Service {
String date = simpleDateFormat.format(new Date(message.getTimeSent())); String date = simpleDateFormat.format(new Date(message.getTimeSent()));
if (bw == null) { if (bw == null) {
bw = new BufferedWriter(new FileWriter( bw = new BufferedWriter(new FileWriter(
new File(dir, contactJid.toBareJid().toString() + ".txt"))); new File(dir, contactJid.asBareJid().toString() + ".txt")));
} }
String jid = null; String jid = null;
switch (message.getStatus()) { switch (message.getStatus()) {
@ -100,7 +100,7 @@ public class ExportLogsService extends Service {
case Message.STATUS_SEND: case Message.STATUS_SEND:
case Message.STATUS_SEND_RECEIVED: case Message.STATUS_SEND_RECEIVED:
case Message.STATUS_SEND_DISPLAYED: case Message.STATUS_SEND_DISPLAYED:
jid = accountJid.toBareJid().toString(); jid = accountJid.asBareJid().toString();
break; break;
} }
if (jid != null) { if (jid != null) {

View File

@ -17,9 +17,9 @@ import eu.siacs.conversations.generator.AbstractGenerator;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded; import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.mam.MamReference; import eu.siacs.conversations.xmpp.mam.MamReference;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded { public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
@ -164,7 +164,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
private void execute(final Query query) { private void execute(final Query query) {
final Account account = query.getAccount(); final Account account = query.getAccount();
if (account.getStatus() == Account.State.ONLINE) { if (account.getStatus() == Account.State.ONLINE) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": running mam query " + query.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": running mam query " + query.toString());
IqPacket packet = this.mXmppConnectionService.getIqGenerator().queryMessageArchiveManagement(query); IqPacket packet = this.mXmppConnectionService.getIqGenerator().queryMessageArchiveManagement(query);
this.mXmppConnectionService.sendIqPacket(account, packet, (a, p) -> { this.mXmppConnectionService.sendIqPacket(account, packet, (a, p) -> {
Element fin = p.findChild("fin", Namespace.MAM); Element fin = p.findChild("fin", Namespace.MAM);
@ -180,7 +180,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} else if (p.getType() == IqPacket.TYPE.RESULT && query.isLegacy()) { } else if (p.getType() == IqPacket.TYPE.RESULT && query.isLegacy()) {
//do nothing //do nothing
} else { } else {
Log.d(Config.LOGTAG, a.getJid().toBareJid().toString() + ": error executing mam: " + p.toString()); Log.d(Config.LOGTAG, a.getJid().asBareJid().toString() + ": error executing mam: " + p.toString());
finalizeQuery(query, true); finalizeQuery(query, true);
} }
}); });
@ -278,7 +278,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
done = done || (query.getActualMessageCount() == 0 && !query.isCatchup()); done = done || (query.getActualMessageCount() == 0 && !query.isCatchup());
this.finalizeQuery(query, done); this.finalizeQuery(query, done);
Log.d(Config.LOGTAG, query.getAccount().getJid().toBareJid() + ": finished mam after " + query.getTotalCount() + "(" + query.getActualMessageCount() + ") messages. messages left=" + Boolean.toString(!done) + " count=" + count); Log.d(Config.LOGTAG, query.getAccount().getJid().asBareJid() + ": finished mam after " + query.getTotalCount() + "(" + query.getActualMessageCount() + ") messages. messages left=" + Boolean.toString(!done) + " count=" + count);
if (query.isCatchup() && query.getActualMessageCount() > 0) { if (query.isCatchup() && query.getActualMessageCount() > 0) {
mXmppConnectionService.getNotificationService().finishBacklog(true, query.getAccount()); mXmppConnectionService.getNotificationService().finishBacklog(true, query.getAccount());
} }
@ -313,7 +313,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
private void kill(Query query) { private void kill(Query query) {
Log.d(Config.LOGTAG, query.getAccount().getJid().toBareJid() + ": killing mam query prematurely"); Log.d(Config.LOGTAG, query.getAccount().getJid().asBareJid() + ": killing mam query prematurely");
query.callback = null; query.callback = null;
this.finalizeQuery(query, false); this.finalizeQuery(query, false);
if (query.isCatchup() && query.getActualMessageCount() > 0) { if (query.isCatchup() && query.getActualMessageCount() > 0) {
@ -324,7 +324,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
private void processPostponed(Query query) { private void processPostponed(Query query) {
query.account.getAxolotlService().processPostponed(); query.account.getAxolotlService().processPostponed();
Log.d(Config.LOGTAG, query.getAccount().getJid().toBareJid() + ": found " + query.pendingReceiptRequests.size() + " pending receipt requests"); Log.d(Config.LOGTAG, query.getAccount().getJid().asBareJid() + ": found " + query.pendingReceiptRequests.size() + " pending receipt requests");
Iterator<ReceiptRequest> iterator = query.pendingReceiptRequests.iterator(); Iterator<ReceiptRequest> iterator = query.pendingReceiptRequests.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
ReceiptRequest rr = iterator.next(); ReceiptRequest rr = iterator.next();
@ -441,7 +441,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
public Jid getWith() { public Jid getWith() {
return conversation == null ? null : conversation.getJid().toBareJid(); return conversation == null ? null : conversation.getJid().asBareJid();
} }
public boolean muc() { public boolean muc() {
@ -506,7 +506,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
if (muc()) { if (muc()) {
return getWith().equals(from); return getWith().equals(from);
} else { } else {
return (from == null) || account.getJid().toBareJid().equals(from.toBareJid()); return (from == null) || account.getJid().asBareJid().equals(from.asBareJid());
} }
} }

View File

@ -156,7 +156,7 @@ public class NotificationService {
} }
} }
} }
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": backlog message count="+count); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": backlog message count="+count);
return count; return count;
} }
@ -190,12 +190,12 @@ public class NotificationService {
private void pushNow(final Message message) { private void pushNow(final Message message) {
mXmppConnectionService.updateUnreadCountBadge(); mXmppConnectionService.updateUnreadCountBadge();
if (!notify(message)) { if (!notify(message)) {
Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because turned off"); Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().asBareJid()+": suppressing notification because turned off");
return; return;
} }
final boolean isScreenOn = mXmppConnectionService.isInteractive(); final boolean isScreenOn = mXmppConnectionService.isInteractive();
if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) { if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because conversation is open"); Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().asBareJid()+": suppressing notification because conversation is open");
return; return;
} }
synchronized (notifications) { synchronized (notifications) {
@ -787,7 +787,7 @@ public class NotificationService {
return; return;
} else if (errors.size() == 1) { } else if (errors.size() == 1) {
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account)); mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString()); mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
} else { } else {
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts)); mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix)); mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));

View File

@ -18,7 +18,7 @@ import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.ui.StartConversationActivity; import eu.siacs.conversations.ui.StartConversationActivity;
import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor; import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class ShortcutService { public class ShortcutService {
@ -109,14 +109,14 @@ public class ShortcutService {
} }
private static String getShortcutId(Contact contact) { private static String getShortcutId(Contact contact) {
return contact.getAccount().getJid().toBareJid().toPreppedString()+"#"+contact.getJid().toBareJid().toPreppedString(); return contact.getAccount().getJid().asBareJid().toString()+"#"+contact.getJid().asBareJid().toString();
} }
private Intent getShortcutIntent(Contact contact) { private Intent getShortcutIntent(Contact contact) {
Intent intent = new Intent(xmppConnectionService, StartConversationActivity.class); Intent intent = new Intent(xmppConnectionService, StartConversationActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("xmpp:"+contact.getJid().toBareJid().toString())); intent.setData(Uri.parse("xmpp:"+contact.getJid().asBareJid().toString()));
intent.putExtra("account",contact.getAccount().getJid().toBareJid().toString()); intent.putExtra("account",contact.getAccount().getJid().asBareJid().toString());
return intent; return intent;
} }

View File

@ -122,8 +122,6 @@ import eu.siacs.conversations.xmpp.Patches;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager; import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived; import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
@ -133,6 +131,7 @@ 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; import me.leolin.shortcutbadger.ShortcutBadger;
import rocks.xmpp.addr.Jid;
public class XmppConnectionService extends Service { public class XmppConnectionService extends Service {
@ -191,7 +190,7 @@ public class XmppConnectionService extends Service {
Element error = packet.findChild("error"); Element error = packet.findChild("error");
String text = error != null ? error.findChildContent("text") : null; String text = error != null ? error.findChildContent("text") : null;
if (text != null) { if (text != null) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
} }
} }
} }
@ -278,7 +277,7 @@ public class XmppConnectionService extends Service {
synchronized (mInProgressAvatarFetches) { synchronized (mInProgressAvatarFetches) {
for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) { for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
final String KEY = iterator.next(); final String KEY = iterator.next();
if (KEY.startsWith(account.getJid().toBareJid() + "_")) { if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
iterator.remove(); iterator.remove();
} }
} }
@ -295,7 +294,7 @@ public class XmppConnectionService extends Service {
if (flexible && catchup) { if (flexible && catchup) {
sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> { sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG, acc.getJid().toBareJid()+": successfully purged offline messages"); Log.d(Config.LOGTAG, acc.getJid().asBareJid()+": successfully purged offline messages");
} }
}); });
} }
@ -317,8 +316,8 @@ public class XmppConnectionService extends Service {
} }
if (account.getStatus() == Account.State.ONLINE) { if (account.getStatus() == Account.State.ONLINE) {
synchronized (mLowPingTimeoutMode) { synchronized (mLowPingTimeoutMode) {
if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) { if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
} }
} }
if (account.setShowErrorNotification(true)) { if (account.setShowErrorNotification(true)) {
@ -327,10 +326,10 @@ public class XmppConnectionService extends Service {
mMessageArchiveService.executePendingQueries(account); mMessageArchiveService.executePendingQueries(account);
if (connection != null && connection.getFeatures().csi()) { if (connection != null && connection.getFeatures().csi()) {
if (checkListeners()) { if (checkListeners()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
connection.sendInactive(); connection.sendInactive();
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
connection.sendActive(); connection.sendActive();
} }
} }
@ -352,7 +351,7 @@ public class XmppConnectionService extends Service {
} else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) { } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
resetSendingToWaiting(account); resetSendingToWaiting(account);
if (account.isEnabled() && isInLowPingTimeoutMode(account)) { if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": went into offline state during low ping mode. reconnecting now"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
reconnectAccount(account, true, false); reconnectAccount(account, true, false);
} else { } else {
int timeToReconnect = mRandom.nextInt(10) + 2; int timeToReconnect = mRandom.nextInt(10) + 2;
@ -367,11 +366,11 @@ public class XmppConnectionService extends Service {
final int next = connection.getTimeToNextAttempt(); final int next = connection.getTimeToNextAttempt();
final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account); final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
if (next <= 0) { if (next <= 0) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode)); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
reconnectAccount(account, true, false); reconnectAccount(account, true, false);
} else { } else {
final int attempt = connection.getAttempt() + 1; final int attempt = connection.getAttempt() + 1;
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode)); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
scheduleWakeUpCall(next, account.getUuid().hashCode()); scheduleWakeUpCall(next, account.getUuid().hashCode());
} }
} }
@ -382,7 +381,7 @@ public class XmppConnectionService extends Service {
private boolean isInLowPingTimeoutMode(Account account) { private boolean isInLowPingTimeoutMode(Account account) {
synchronized (mLowPingTimeoutMode) { synchronized (mLowPingTimeoutMode) {
return mLowPingTimeoutMode.contains(account.getJid().toBareJid()); return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
} }
} }
@ -406,7 +405,7 @@ public class XmppConnectionService extends Service {
public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1); public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
private static String generateFetchKey(Account account, final Avatar avatar) { private static String generateFetchKey(Account account, final Avatar avatar) {
return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum; return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
} }
public boolean areMessagesInitialized() { public boolean areMessagesInitialized() {
@ -499,7 +498,7 @@ public class XmppConnectionService extends Service {
if ("never".equals(compressPictures) if ("never".equals(compressPictures)
|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri)) || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
|| (mimeType != null && mimeType.endsWith("/gif"))) { || (mimeType != null && mimeType.endsWith("/gif"))) {
Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": not compressing picture. sending as file"); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
attachFileToConversation(conversation, uri, mimeType, callback); attachFileToConversation(conversation, uri, mimeType, callback);
return; return;
} }
@ -683,7 +682,7 @@ public class XmppConnectionService extends Service {
for (Account account : pingCandidates) { for (Account account : pingCandidates) {
final boolean lowTimeout = isInLowPingTimeoutMode(account); final boolean lowTimeout = isInLowPingTimeoutMode(account);
account.getXmppConnection().sendPing(); account.getXmppConnection().sendPing();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode()); scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
} }
} }
@ -721,11 +720,11 @@ public class XmppConnectionService extends Service {
long lastSent = account.getXmppConnection().getLastPingSent(); long lastSent = account.getXmppConnection().getLastPingSent();
long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000; long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime(); long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000; int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime(); long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
if (lastSent > lastReceived) { if (lastSent > lastReceived) {
if (pingTimeoutIn < 0) { if (pingTimeoutIn < 0) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
this.reconnectAccount(account, true, interactive); this.reconnectAccount(account, true, interactive);
} else { } else {
int secs = (int) (pingTimeoutIn / 1000); int secs = (int) (pingTimeoutIn / 1000);
@ -735,15 +734,15 @@ public class XmppConnectionService extends Service {
pingCandidates.add(account); pingCandidates.add(account);
if (isAccountPushed) { if (isAccountPushed) {
pingNow = true; pingNow = true;
if (mLowPingTimeoutMode.add(account.getJid().toBareJid())) { if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": entering low ping timeout mode"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
} }
} else if (msToNextPing <= 0) { } else if (msToNextPing <= 0) {
pingNow = true; pingNow = true;
} else { } else {
this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode()); this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) { if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
} }
} }
} }
@ -898,7 +897,7 @@ public class XmppConnectionService extends Service {
private void dismissErrorNotifications() { private void dismissErrorNotifications() {
for (final Account account : this.accounts) { for (final Account account : this.accounts) {
if (account.hasErrorStatus()) { if (account.hasErrorStatus()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": dismissing error notification"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
if (account.setShowErrorNotification(false)) { if (account.setShowErrorNotification(false)) {
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
} }
@ -1318,10 +1317,10 @@ public class XmppConnectionService extends Service {
public void fetchRosterFromServer(final Account account) { public void fetchRosterFromServer(final Account account) {
final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET); final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
if (!"".equals(account.getRosterVersion())) { if (!"".equals(account.getRosterVersion())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().asBareJid()
+ ": fetching roster version " + account.getRosterVersion()); + ": fetching roster version " + account.getRosterVersion());
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
} }
iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion()); iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
sendIqPacket(account, iqPacket, mIqParser); sendIqPacket(account, iqPacket, mIqParser);
@ -1360,7 +1359,7 @@ public class XmppConnectionService extends Service {
} }
account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values())); account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values()));
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not fetch bookmarks");
} }
} }
}; };
@ -1368,7 +1367,7 @@ public class XmppConnectionService extends Service {
} }
public void pushBookmarks(Account account) { public void pushBookmarks(Account account) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": pushing bookmarks"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks");
IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET); IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
Element query = iqPacket.query("jabber:iq:private"); Element query = iqPacket.query("jabber:iq:private");
Element storage = query.addChild("storage", "storage:bookmarks"); Element storage = query.addChild("storage", "storage:bookmarks");
@ -1458,8 +1457,8 @@ public class XmppConnectionService extends Service {
for (Bundle phoneContact : phoneContacts) { for (Bundle phoneContact : phoneContacts) {
Jid jid; Jid jid;
try { try {
jid = Jid.fromString(phoneContact.getString("jid")); jid = Jid.of(phoneContact.getString("jid"));
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
continue; continue;
} }
final Contact contact = account.getRoster().getContact(jid); final Contact contact = account.getRoster().getContact(jid);
@ -1628,7 +1627,7 @@ public class XmppConnectionService extends Service {
} }
for (final Conversation conversation : haystack) { for (final Conversation conversation : haystack) {
if ((account == null || conversation.getAccount() == account) if ((account == null || conversation.getAccount() == account)
&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) { && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
return conversation; return conversation;
} }
} }
@ -1672,7 +1671,7 @@ public class XmppConnectionService extends Service {
conversation.setContactJid(jid); conversation.setContactJid(jid);
} else { } else {
conversation.setMode(Conversation.MODE_SINGLE); conversation.setMode(Conversation.MODE_SINGLE);
conversation.setContactJid(jid.toBareJid()); conversation.setContactJid(jid.asBareJid());
} }
databaseBackend.updateConversation(conversation); databaseBackend.updateConversation(conversation);
loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false); loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
@ -1682,13 +1681,13 @@ public class XmppConnectionService extends Service {
if (contact != null) { if (contact != null) {
conversationName = contact.getDisplayName(); conversationName = contact.getDisplayName();
} else { } else {
conversationName = jid.getLocalpart(); conversationName = jid.getLocal();
} }
if (muc) { if (muc) {
conversation = new Conversation(conversationName, account, jid, conversation = new Conversation(conversationName, account, jid,
Conversation.MODE_MULTI); Conversation.MODE_MULTI);
} else { } else {
conversation = new Conversation(conversationName, account, jid.toBareJid(), conversation = new Conversation(conversationName, account, jid.asBareJid(),
Conversation.MODE_SINGLE); Conversation.MODE_SINGLE);
} }
this.databaseBackend.createConversation(conversation); this.databaseBackend.createConversation(conversation);
@ -1795,7 +1794,7 @@ public class XmppConnectionService extends Service {
callback.onAccountCreated(account); callback.onAccountCreated(account);
if (Config.X509_VERIFICATION) { if (Config.X509_VERIFICATION) {
try { try {
getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA"); getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
} catch (CertificateException e) { } catch (CertificateException e) {
callback.informUser(R.string.certificate_chain_is_not_trusted); callback.informUser(R.string.certificate_chain_is_not_trusted);
} }
@ -1812,16 +1811,16 @@ public class XmppConnectionService extends Service {
} }
public void updateKeyInAccount(final Account account, final String alias) { public void updateKeyInAccount(final Account account, final String alias) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": update key in account " + alias); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
try { try {
X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias); X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + " loaded certificate chain"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]); Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
if (info == null) { if (info == null) {
showErrorToastInUi(R.string.certificate_does_not_contain_jid); showErrorToastInUi(R.string.certificate_does_not_contain_jid);
return; return;
} }
if (account.getJid().toBareJid().equals(info.first)) { if (account.getJid().asBareJid().equals(info.first)) {
account.setPrivateKeyAlias(alias); account.setPrivateKeyAlias(alias);
account.setDisplayName(info.second); account.setDisplayName(info.second);
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
@ -1886,7 +1885,7 @@ public class XmppConnectionService extends Service {
} }
final Runnable runnable = () -> { final Runnable runnable = () -> {
if (!databaseBackend.deleteAccount(account)) { if (!databaseBackend.deleteAccount(account)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": unable to delete account"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
} }
}; };
mDatabaseWriterExecutor.execute(runnable); mDatabaseWriterExecutor.execute(runnable);
@ -2194,7 +2193,7 @@ public class XmppConnectionService extends Service {
Account account = conversation.getAccount(); Account account = conversation.getAccount();
final MucOptions mucOptions = conversation.getMucOptions(); final MucOptions mucOptions = conversation.getMucOptions();
final Jid joinJid = mucOptions.getSelf().getFullJid(); final Jid joinJid = mucOptions.getSelf().getFullJid();
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null); PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
packet.setTo(joinJid); packet.setTo(joinJid);
Element x = packet.addChild("x", "http://jabber.org/protocol/muc"); Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
@ -2286,7 +2285,7 @@ public class XmppConnectionService extends Service {
} }
} else { } else {
success = false; success = false;
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().toBareJid()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
} }
++i; ++i;
if (i >= affiliations.length) { if (i >= affiliations.length) {
@ -2298,7 +2297,7 @@ public class XmppConnectionService extends Service {
Jid jid = iterator.next(); Jid jid = iterator.next();
if (!members.contains(jid)) { if (!members.contains(jid)) {
iterator.remove(); iterator.remove();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
changed = true; changed = true;
} }
} }
@ -2307,7 +2306,7 @@ public class XmppConnectionService extends Service {
updateConversation(conversation); updateConversation(conversation);
} }
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": retrieved members for " + conversation.getJid().toBareJid() + ": " + conversation.getMucOptions().getMembers()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved members for " + conversation.getJid().asBareJid() + ": " + conversation.getMucOptions().getMembers());
getAvatarService().clear(conversation); getAvatarService().clear(conversation);
updateMucRosterUi(); updateMucRosterUi();
updateConversationUi(); updateConversationUi();
@ -2317,7 +2316,7 @@ public class XmppConnectionService extends Service {
for (String affiliation : affiliations) { for (String affiliation : affiliations) {
sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback); sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching members for " + conversation.getName()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
} }
public void providePasswordForMuc(Conversation conversation, String password) { public void providePasswordForMuc(Conversation conversation, String password) {
@ -2353,8 +2352,8 @@ public class XmppConnectionService extends Service {
} }
Bookmark bookmark = conversation.getBookmark(); Bookmark bookmark = conversation.getBookmark();
if (bookmark != null && !full.getResourcepart().equals(bookmark.getNick())) { if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
bookmark.setNick(full.getResourcepart()); bookmark.setNick(full.getResource());
pushBookmarks(bookmark.getAccount()); pushBookmarks(bookmark.getAccount());
} }
} }
@ -2420,7 +2419,7 @@ public class XmppConnectionService extends Service {
if (bookmark != null) { if (bookmark != null) {
bookmark.setConversation(null); bookmark.setConversation(null);
} }
Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": leaving muc " + conversation.getJid()); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
} else { } else {
account.pendingConferenceLeaves.add(conversation); account.pendingConferenceLeaves.add(conversation);
} }
@ -2449,7 +2448,7 @@ public class XmppConnectionService extends Service {
final String subject, final String subject,
final Iterable<Jid> jids, final Iterable<Jid> jids,
final UiCallback<Conversation> callback) { final UiCallback<Conversation> callback) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
if (account.getStatus() == Account.State.ONLINE) { if (account.getStatus() == Account.State.ONLINE) {
try { try {
String server = findConferenceServer(account); String server = findConferenceServer(account);
@ -2459,7 +2458,7 @@ public class XmppConnectionService extends Service {
} }
return false; return false;
} }
final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null); final Jid jid = Jid.of(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
final Conversation conversation = findOrCreateConversation(account, jid, true, false, true); final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
joinMuc(conversation, new OnConferenceJoined() { joinMuc(conversation, new OnConferenceJoined() {
@Override @Override
@ -2474,7 +2473,7 @@ public class XmppConnectionService extends Service {
invite(conversation, invite); invite(conversation, invite);
} }
if (account.countPresences() > 1) { if (account.countPresences() > 1) {
directInvite(conversation, account.getJid().toBareJid()); directInvite(conversation, account.getJid().asBareJid());
} }
saveConversationAsBookmark(conversation, subject); saveConversationAsBookmark(conversation, subject);
if (callback != null) { if (callback != null) {
@ -2493,7 +2492,7 @@ public class XmppConnectionService extends Service {
} }
}); });
return true; return true;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
if (callback != null) { if (callback != null) {
callback.error(R.string.conference_creation_failed, null); callback.error(R.string.conference_creation_failed, null);
} }
@ -2513,7 +2512,7 @@ public class XmppConnectionService extends Service {
public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) { public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
IqPacket request = new IqPacket(IqPacket.TYPE.GET); IqPacket request = new IqPacket(IqPacket.TYPE.GET);
request.setTo(conversation.getJid().toBareJid()); request.setTo(conversation.getJid().asBareJid());
request.query("http://jabber.org/protocol/disco#info"); request.query("http://jabber.org/protocol/disco#info");
sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() { sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
@Override @Override
@ -2537,7 +2536,7 @@ public class XmppConnectionService extends Service {
if (callback != null) { if (callback != null) {
callback.onConferenceConfigurationFetched(conversation); callback.onConferenceConfigurationFetched(conversation);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetched muc configuration for " + conversation.getJid().toBareJid() + " - " + features.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetched muc configuration for " + conversation.getJid().asBareJid() + " - " + features.toString());
updateConversationUi(); updateConversationUi();
} else if (packet.getType() == IqPacket.TYPE.ERROR) { } else if (packet.getType() == IqPacket.TYPE.ERROR) {
if (callback != null) { if (callback != null) {
@ -2549,7 +2548,7 @@ public class XmppConnectionService extends Service {
} }
public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) { public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
pushNodeConfiguration(account, account.getJid().toBareJid(), node, options, callback); pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
} }
public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) { public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
@ -2585,7 +2584,7 @@ public class XmppConnectionService extends Service {
public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) { public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
IqPacket request = new IqPacket(IqPacket.TYPE.GET); IqPacket request = new IqPacket(IqPacket.TYPE.GET);
request.setTo(conversation.getJid().toBareJid()); request.setTo(conversation.getJid().asBareJid());
request.query("http://jabber.org/protocol/muc#owner"); request.query("http://jabber.org/protocol/muc#owner");
sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() { sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
@Override @Override
@ -2594,7 +2593,7 @@ public class XmppConnectionService extends Service {
Data data = Data.parse(packet.query().findChild("x", Namespace.DATA)); Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
data.submit(options); data.submit(options);
IqPacket set = new IqPacket(IqPacket.TYPE.SET); IqPacket set = new IqPacket(IqPacket.TYPE.SET);
set.setTo(conversation.getJid().toBareJid()); set.setTo(conversation.getJid().asBareJid());
set.query("http://jabber.org/protocol/muc#owner").addChild(data); set.query("http://jabber.org/protocol/muc#owner").addChild(data);
sendIqPacket(account, set, new OnIqPacketReceived() { sendIqPacket(account, set, new OnIqPacketReceived() {
@Override @Override
@ -2631,7 +2630,7 @@ public class XmppConnectionService extends Service {
} }
public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) { public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
final Jid jid = user.toBareJid(); final Jid jid = user.asBareJid();
IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString()); IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() { sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
@Override @Override
@ -2784,7 +2783,7 @@ public class XmppConnectionService extends Service {
getAvatarService().clear(account); getAvatarService().clear(account);
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
if (callback != null) { if (callback != null) {
callback.success(avatar); callback.success(avatar);
} }
@ -2797,7 +2796,7 @@ public class XmppConnectionService extends Service {
}); });
} else { } else {
Element error = result.findChild("error"); Element error = result.findChild("error");
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : "")); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
if (callback != null) { if (callback != null) {
callback.error(R.string.error_publish_avatar_server_reject, avatar); callback.error(R.string.error_publish_avatar_server_reject, avatar);
} }
@ -2808,7 +2807,7 @@ public class XmppConnectionService extends Service {
public void republishAvatarIfNeeded(Account account) { public void republishAvatarIfNeeded(Account account) {
if (account.getAxolotlService().isPepBroken()) { if (account.getAxolotlService().isPepBroken()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping republication of avatar because pep is broken"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
return; return;
} }
IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null); IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
@ -2839,10 +2838,10 @@ public class XmppConnectionService extends Service {
if (serverAvatar == null && account.getAvatar() != null) { if (serverAvatar == null && account.getAvatar() != null) {
Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar()); Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
if (avatar != null) { if (avatar != null) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": avatar on server was null. republishing"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null); publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
} else { } else {
Log.e(Config.LOGTAG, account.getJid().toBareJid() + ": error rereading avatar"); Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
} }
} }
} }
@ -2881,13 +2880,13 @@ public class XmppConnectionService extends Service {
synchronized (mInProgressAvatarFetches) { synchronized (mInProgressAvatarFetches) {
mInProgressAvatarFetches.remove(generateFetchKey(account, avatar)); mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
} }
final String ERROR = account.getJid().toBareJid() final String ERROR = account.getJid().asBareJid()
+ ": fetching avatar for " + avatar.owner + " failed "; + ": fetching avatar for " + avatar.owner + " failed ";
if (result.getType() == IqPacket.TYPE.RESULT) { if (result.getType() == IqPacket.TYPE.RESULT) {
avatar.image = mIqParser.avatarData(result); avatar.image = mIqParser.avatarData(result);
if (avatar.image != null) { if (avatar.image != null) {
if (getFileBackend().save(avatar)) { if (getFileBackend().save(avatar)) {
if (account.getJid().toBareJid().equals(avatar.owner)) { if (account.getJid().asBareJid().equals(avatar.owner)) {
if (account.setAvatar(avatar.getFilename())) { if (account.setAvatar(avatar.getFilename())) {
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
} }
@ -2905,7 +2904,7 @@ public class XmppConnectionService extends Service {
if (callback != null) { if (callback != null) {
callback.success(avatar); callback.success(avatar);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().asBareJid()
+ ": successfully fetched pep avatar for " + avatar.owner); + ": successfully fetched pep avatar for " + avatar.owner);
return; return;
} }
@ -2944,11 +2943,11 @@ public class XmppConnectionService extends Service {
if (image != null) { if (image != null) {
avatar.image = image; avatar.image = image;
if (getFileBackend().save(avatar)) { if (getFileBackend().save(avatar)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().asBareJid()
+ ": successfully fetched vCard avatar for " + avatar.owner); + ": successfully fetched vCard avatar for " + avatar.owner);
if (avatar.owner.isBareJid()) { if (avatar.owner.isBareJid()) {
if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) { if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": had no avatar. replacing with vcard"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
account.setAvatar(avatar.getFilename()); account.setAvatar(avatar.getFilename());
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
getAvatarService().clear(account); getAvatarService().clear(account);
@ -2961,7 +2960,7 @@ public class XmppConnectionService extends Service {
} }
updateConversationUi(); updateConversationUi();
} else { } else {
Conversation conversation = find(account, avatar.owner.toBareJid()); Conversation conversation = find(account, avatar.owner.asBareJid());
if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) { if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner); MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
if (user != null) { if (user != null) {
@ -2993,7 +2992,7 @@ public class XmppConnectionService extends Service {
if (items != null) { if (items != null) {
Avatar avatar = Avatar.parseMetadata(items); Avatar avatar = Avatar.parseMetadata(items);
if (avatar != null) { if (avatar != null) {
avatar.owner = account.getJid().toBareJid(); avatar.owner = account.getJid().asBareJid();
if (fileBackend.isAvatarCached(avatar)) { if (fileBackend.isAvatarCached(avatar)) {
if (account.setAvatar(avatar.getFilename())) { if (account.setAvatar(avatar.getFilename())) {
databaseBackend.updateAccount(account); databaseBackend.updateAccount(account);
@ -3079,7 +3078,7 @@ public class XmppConnectionService extends Service {
} }
public void invite(Conversation conversation, Jid contact) { public void invite(Conversation conversation, Jid contact) {
Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid()); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
MessagePacket packet = mMessageGenerator.invite(conversation, contact); MessagePacket packet = mMessageGenerator.invite(conversation, contact);
sendMessagePacket(conversation.getAccount(), packet); sendMessagePacket(conversation.getAccount(), packet);
} }
@ -3112,7 +3111,7 @@ public class XmppConnectionService extends Service {
return null; return null;
} }
for (Conversation conversation : getConversations()) { for (Conversation conversation : getConversations()) {
if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) { if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid); final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
if (message != null) { if (message != null) {
markMessage(message, status, errorMessage); markMessage(message, status, errorMessage);
@ -3276,7 +3275,7 @@ public class XmppConnectionService extends Service {
public Account findAccountByJid(final Jid accountJid) { public Account findAccountByJid(final Jid accountJid) {
for (Account account : this.accounts) { for (Account account : this.accounts) {
if (account.getJid().toBareJid().equals(accountJid.toBareJid())) { if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
return account; return account;
} }
} }
@ -3341,7 +3340,7 @@ public class XmppConnectionService extends Service {
&& markable != null && markable != null
&& (markable.trusted() || isPrivateAndNonAnonymousMuc) && (markable.trusted() || isPrivateAndNonAnonymousMuc)
&& markable.getRemoteMsgId() != null) { && markable.getRemoteMsgId() != null) {
Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString()); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
Account account = conversation.getAccount(); Account account = conversation.getAccount();
final Jid to = markable.getCounterpart(); final Jid to = markable.getCounterpart();
final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI; final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
@ -3427,7 +3426,7 @@ public class XmppConnectionService extends Service {
} }
for (Bookmark bookmark : account.getBookmarks()) { for (Bookmark bookmark : account.getBookmarks()) {
final Jid jid = bookmark.getJid(); final Jid jid = bookmark.getJid();
final String s = jid == null ? null : jid.getDomainpart(); final String s = jid == null ? null : jid.getDomain();
if (s != null && !mucServers.contains(s)) { if (s != null && !mucServers.contains(s)) {
mucServers.add(s); mucServers.add(s);
} }
@ -3513,7 +3512,7 @@ public class XmppConnectionService extends Service {
} }
private void sendOfflinePresence(final Account account) { private void sendOfflinePresence(final Account account) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending offline presence"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account)); sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
} }
@ -3545,7 +3544,7 @@ public class XmppConnectionService extends Service {
ArrayList<Contact> contacts = new ArrayList<>(); ArrayList<Contact> contacts = new ArrayList<>();
for (Account account : getAccounts()) { for (Account account : getAccounts()) {
if ((account.isEnabled() || accountJid != null) if ((account.isEnabled() || accountJid != null)
&& (accountJid == null || accountJid.equals(account.getJid().toBareJid().toString()))) { && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
Contact contact = account.getRoster().getContactFromRoster(jid); Contact contact = account.getRoster().getContactFromRoster(jid);
if (contact != null) { if (contact != null) {
contacts.add(contact); contacts.add(contact);
@ -3557,7 +3556,7 @@ public class XmppConnectionService extends Service {
public Conversation findFirstMuc(Jid jid) { public Conversation findFirstMuc(Jid jid) {
for (Conversation conversation : getConversations()) { for (Conversation conversation : getConversations()) {
if (conversation.getAccount().isEnabled() && conversation.getJid().toBareJid().equals(jid.toBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) { if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
return conversation; return conversation;
} }
} }
@ -3643,17 +3642,17 @@ public class XmppConnectionService extends Service {
public boolean removeBlockedConversations(final Account account, final Jid blockedJid) { public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
boolean removed = false; boolean removed = false;
synchronized (this.conversations) { synchronized (this.conversations) {
boolean domainJid = blockedJid.isDomainJid(); boolean domainJid = blockedJid.getLocal() == null;
for (Conversation conversation : this.conversations) { for (Conversation conversation : this.conversations) {
boolean jidMatches = (domainJid && blockedJid.getDomainpart().equals(conversation.getJid().getDomainpart())) boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
|| blockedJid.equals(conversation.getJid().toBareJid()); || blockedJid.equals(conversation.getJid().asBareJid());
if (conversation.getAccount() == account if (conversation.getAccount() == account
&& conversation.getMode() == Conversation.MODE_SINGLE && conversation.getMode() == Conversation.MODE_SINGLE
&& jidMatches) { && jidMatches) {
this.conversations.remove(conversation); this.conversations.remove(conversation);
markRead(conversation); markRead(conversation);
conversation.setStatus(Conversation.STATUS_ARCHIVED); conversation.setStatus(Conversation.STATUS_ARCHIVED);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": archiving conversation " + conversation.getJid().toBareJid() + " because jid was blocked"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
updateConversation(conversation); updateConversation(conversation);
removed = true; removed = true;
} }
@ -3685,7 +3684,7 @@ public class XmppConnectionService extends Service {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.ERROR) { if (packet.getType() == IqPacket.TYPE.ERROR) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not publish nick");
} }
} }
}); });
@ -3716,7 +3715,7 @@ public class XmppConnectionService extends Service {
IqPacket request = new IqPacket(IqPacket.TYPE.GET); IqPacket request = new IqPacket(IqPacket.TYPE.GET);
request.setTo(jid); request.setTo(jid);
request.query("http://jabber.org/protocol/disco#info"); request.query("http://jabber.org/protocol/disco#info");
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": making disco request for " + key.second + " to " + jid); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
sendIqPacket(account, request, new OnIqPacketReceived() { sendIqPacket(account, request, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket discoPacket) { public void onIqPacketReceived(Account account, IqPacket discoPacket) {
@ -3726,7 +3725,7 @@ public class XmppConnectionService extends Service {
databaseBackend.insertDiscoveryResult(disco); databaseBackend.insertDiscoveryResult(disco);
injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco); injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
} }
} }
account.inProgressDiscoFetches.remove(key); account.inProgressDiscoFetches.remove(key);
@ -3802,9 +3801,9 @@ public class XmppConnectionService extends Service {
public void saveConversationAsBookmark(Conversation conversation, String name) { public void saveConversationAsBookmark(Conversation conversation, String name) {
Account account = conversation.getAccount(); Account account = conversation.getAccount();
Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid()); Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
if (!conversation.getJid().isBareJid()) { if (!conversation.getJid().isBareJid()) {
bookmark.setNick(conversation.getJid().getResourcepart()); bookmark.setNick(conversation.getJid().getResource());
} }
if (name != null && !name.trim().isEmpty()) { if (name != null && !name.trim().isEmpty()) {
bookmark.setBookmarkName(name.trim()); bookmark.setBookmarkName(name.trim());

View File

@ -16,6 +16,7 @@ import android.widget.Toast;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Blockable; import eu.siacs.conversations.entities.Blockable;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import rocks.xmpp.addr.Jid;
public final class BlockContactDialog { public final class BlockContactDialog {
public static void show(final XmppActivity xmppActivity, final Blockable blockable) { public static void show(final XmppActivity xmppActivity, final Blockable blockable) {
@ -32,14 +33,14 @@ public final class BlockContactDialog {
String value; String value;
SpannableString spannable; SpannableString spannable;
if (blockable.getJid().isDomainJid() || blockable.getAccount().isBlocked(blockable.getJid().toDomainJid())) { if (blockable.getJid().getLocal() == null || blockable.getAccount().isBlocked(Jid.ofDomain(blockable.getJid().getDomain()))) {
builder.setTitle(isBlocked ? R.string.action_unblock_domain : R.string.action_block_domain); builder.setTitle(isBlocked ? R.string.action_unblock_domain : R.string.action_block_domain);
value = blockable.getJid().toDomainJid().toString(); value = Jid.ofDomain(blockable.getJid().getDomain()).toString();
spannable = new SpannableString(xmppActivity.getString(isBlocked ? R.string.unblock_domain_text : R.string.block_domain_text, value)); spannable = new SpannableString(xmppActivity.getString(isBlocked ? R.string.unblock_domain_text : R.string.block_domain_text, value));
} else { } else {
int resBlockAction = blockable instanceof Conversation && ((Conversation) blockable).isWithStranger() ? R.string.block_stranger : R.string.action_block_contact; int resBlockAction = blockable instanceof Conversation && ((Conversation) blockable).isWithStranger() ? R.string.block_stranger : R.string.action_block_contact;
builder.setTitle(isBlocked ? R.string.action_unblock_contact : resBlockAction); builder.setTitle(isBlocked ? R.string.action_unblock_contact : resBlockAction);
value = blockable.getJid().toBareJid().toString(); value = blockable.getJid().asBareJid().toString();
spannable = new SpannableString(xmppActivity.getString(isBlocked ? R.string.unblock_contact_text : R.string.block_contact_text, value)); spannable = new SpannableString(xmppActivity.getString(isBlocked ? R.string.unblock_contact_text : R.string.block_contact_text, value));
} }
int start = spannable.toString().indexOf(value); int start = spannable.toString().indexOf(value);

View File

@ -16,7 +16,7 @@ import eu.siacs.conversations.R;
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.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class BlocklistActivity extends AbstractSearchableListItemActivity implements OnUpdateBlocklist { public class BlocklistActivity extends AbstractSearchableListItemActivity implements OnUpdateBlocklist {
private List<String> mKnownHosts = new ArrayList<>(); private List<String> mKnownHosts = new ArrayList<>();
@ -87,7 +87,7 @@ public class BlocklistActivity extends AbstractSearchableListItemActivity implem
EnterJidDialog dialog = new EnterJidDialog( EnterJidDialog dialog = new EnterJidDialog(
this, mKnownHosts, null, this, mKnownHosts, null,
getString(R.string.block_jabber_id), getString(R.string.block), getString(R.string.block_jabber_id), getString(R.string.block),
null, account.getJid().toBareJid().toString(), true null, account.getJid().asBareJid().toString(), true
); );
dialog.setOnEnterJidDialogPositiveListener(new EnterJidDialog.OnEnterJidDialogPositiveListener() { dialog.setOnEnterJidDialogPositiveListener(new EnterJidDialog.OnEnterJidDialogPositiveListener() {

View File

@ -29,7 +29,7 @@ import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.ListItem; import eu.siacs.conversations.entities.ListItem;
import eu.siacs.conversations.entities.MucOptions; import eu.siacs.conversations.entities.MucOptions;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class ChooseContactActivity extends AbstractSearchableListItemActivity { public class ChooseContactActivity extends AbstractSearchableListItemActivity {
private List<String> mActivatedAccounts = new ArrayList<>(); private List<String> mActivatedAccounts = new ArrayList<>();
@ -123,7 +123,7 @@ public class ChooseContactActivity extends AbstractSearchableListItemActivity {
data.putExtra("contact", mListItem.getJid().toString()); data.putExtra("contact", mListItem.getJid().toString());
String account = request.getStringExtra(EXTRA_ACCOUNT); String account = request.getStringExtra(EXTRA_ACCOUNT);
if (account == null && mListItem instanceof Contact) { if (account == null && mListItem instanceof Contact) {
account = ((Contact) mListItem).getAccount().getJid().toBareJid().toString(); account = ((Contact) mListItem).getAccount().getJid().asBareJid().toString();
} }
data.putExtra(EXTRA_ACCOUNT, account); data.putExtra(EXTRA_ACCOUNT, account);
data.putExtra("conversation", data.putExtra("conversation",
@ -172,7 +172,7 @@ public class ChooseContactActivity extends AbstractSearchableListItemActivity {
if (account.getStatus() != Account.State.DISABLED) { if (account.getStatus() != Account.State.DISABLED) {
for (final Contact contact : account.getRoster().getContacts()) { for (final Contact contact : account.getRoster().getContacts()) {
if (contact.showInRoster() && if (contact.showInRoster() &&
!filterContacts.contains(contact.getJid().toBareJid().toString()) !filterContacts.contains(contact.getJid().asBareJid().toString())
&& contact.match(this, needle)) { && contact.match(this, needle)) {
getListItems().add(contact); getListItems().add(contact);
} }
@ -241,9 +241,9 @@ public class ChooseContactActivity extends AbstractSearchableListItemActivity {
for (Account account : xmppConnectionService.getAccounts()) { for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() != Account.State.DISABLED) { if (account.getStatus() != Account.State.DISABLED) {
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
this.mActivatedAccounts.add(account.getJid().getLocalpart()); this.mActivatedAccounts.add(account.getJid().getLocal());
} else { } else {
this.mActivatedAccounts.add(account.getJid().toBareJid().toString()); this.mActivatedAccounts.add(account.getJid().asBareJid().toString());
} }
} }
} }
@ -257,17 +257,17 @@ public class ChooseContactActivity extends AbstractSearchableListItemActivity {
for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) { for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
Jid jid = user.getRealJid(); Jid jid = user.getRealJid();
if (jid != null) { if (jid != null) {
contacts.add(jid.toBareJid().toString()); contacts.add(jid.asBareJid().toString());
} }
} }
} else { } else {
contacts.add(conversation.getJid().toBareJid().toString()); contacts.add(conversation.getJid().asBareJid().toString());
} }
intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()])); intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
intent.putExtra("conversation", conversation.getUuid()); intent.putExtra("conversation", conversation.getUuid());
intent.putExtra("multiple", true); intent.putExtra("multiple", true);
intent.putExtra("show_enter_jid", true); intent.putExtra("show_enter_jid", true);
intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
return intent; return intent;
} }
} }

View File

@ -50,7 +50,7 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate; import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
import eu.siacs.conversations.services.XmppConnectionService.OnMucRosterUpdate; import eu.siacs.conversations.services.XmppConnectionService.OnMucRosterUpdate;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class ConferenceDetailsActivity extends XmppActivity implements OnConversationUpdate, OnMucRosterUpdate, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged, XmppConnectionService.OnConfigurationPushed { public class ConferenceDetailsActivity extends XmppActivity implements OnConversationUpdate, OnMucRosterUpdate, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged, XmppConnectionService.OnConfigurationPushed {
public static final String ACTION_VIEW_MUC = "view_muc"; public static final String ACTION_VIEW_MUC = "view_muc";
@ -329,9 +329,9 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
protected String getShareableUri(boolean http) { protected String getShareableUri(boolean http) {
if (mConversation != null) { if (mConversation != null) {
if (http) { if (http) {
return "https://conversations.im/j/"+ mConversation.getJid().toBareJid(); return "https://conversations.im/j/"+ mConversation.getJid().asBareJid();
} else { } else {
return "xmpp:"+mConversation.getJid().toBareJid()+"?join"; return "xmpp:"+mConversation.getJid().asBareJid()+"?join";
} }
} else { } else {
return null; return null;
@ -378,7 +378,7 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
if (contact != null && contact.showInRoster()) { if (contact != null && contact.showInRoster()) {
name = contact.getDisplayName(); name = contact.getDisplayName();
} else if (user.getRealJid() != null){ } else if (user.getRealJid() != null){
name = user.getRealJid().toBareJid().toString(); name = user.getRealJid().asBareJid().toString();
} else { } else {
name = user.getName(); name = user.getName();
} }
@ -502,7 +502,7 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
protected void startConversation(User user) { protected void startConversation(User user) {
if (user.getRealJid() != null) { if (user.getRealJid() != null) {
Conversation conversation = xmppConnectionService.findOrCreateConversation(this.mConversation.getAccount(),user.getRealJid().toBareJid(),false,true); Conversation conversation = xmppConnectionService.findOrCreateConversation(this.mConversation.getAccount(),user.getRealJid().asBareJid(),false,true);
switchToConversation(conversation); switchToConversation(conversation);
} }
} }
@ -544,14 +544,14 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
final User self = mucOptions.getSelf(); final User self = mucOptions.getSelf();
String account; String account;
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
account = mConversation.getAccount().getJid().getLocalpart(); account = mConversation.getAccount().getJid().getLocal();
} else { } else {
account = mConversation.getAccount().getJid().toBareJid().toString(); account = mConversation.getAccount().getJid().asBareJid().toString();
} }
mAccountJid.setText(getString(R.string.using_account, account)); mAccountJid.setText(getString(R.string.using_account, account));
mYourPhoto.setImageBitmap(avatarService().get(mConversation.getAccount(), getPixel(48))); mYourPhoto.setImageBitmap(avatarService().get(mConversation.getAccount(), getPixel(48)));
setTitle(mConversation.getName()); setTitle(mConversation.getName());
mFullJid.setText(mConversation.getJid().toBareJid().toString()); mFullJid.setText(mConversation.getJid().asBareJid().toString());
mYourNick.setText(mucOptions.getActualNick()); mYourNick.setText(mucOptions.getActualNick());
TextView mRoleAffiliaton = (TextView) findViewById(R.id.muc_role); TextView mRoleAffiliaton = (TextView) findViewById(R.id.muc_role);
if (mucOptions.online()) { if (mucOptions.online()) {
@ -680,7 +680,7 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
@Override @Override
public void onAffiliationChangeFailed(Jid jid, int resId) { public void onAffiliationChangeFailed(Jid jid, int resId) {
displayToast(getString(resId,jid.toBareJid().toString())); displayToast(getString(resId,jid.asBareJid().toString()));
} }
@Override @Override
@ -745,7 +745,7 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
imageView.setImageBitmap(bm); imageView.setImageBitmap(bm);
imageView.setBackgroundColor(0x00000000); imageView.setBackgroundColor(0x00000000);
} else { } else {
String seed = user.getRealJid() != null ? user.getRealJid().toBareJid().toString() : null; String seed = user.getRealJid() != null ? user.getRealJid().asBareJid().toString() : null;
imageView.setBackgroundColor(UIHelper.getColorForName(seed == null ? user.getName() : seed)); imageView.setBackgroundColor(UIHelper.getColorForName(seed == null ? user.getName() : seed));
imageView.setImageDrawable(null); imageView.setImageDrawable(null);
final BitmapWorkerTask task = new BitmapWorkerTask(imageView); final BitmapWorkerTask task = new BitmapWorkerTask(imageView);

View File

@ -44,8 +44,7 @@ import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ContactDetailsActivity extends OmemoActivity implements OnAccountUpdate, OnRosterUpdate, OnUpdateBlocklist, OnKeyStatusUpdated { public class ContactDetailsActivity extends OmemoActivity implements OnAccountUpdate, OnRosterUpdate, OnUpdateBlocklist, OnKeyStatusUpdated {
public static final String ACTION_VIEW_CONTACT = "view_contact"; public static final String ACTION_VIEW_CONTACT = "view_contact";
@ -168,7 +167,7 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
protected String getShareableUri(boolean http) { protected String getShareableUri(boolean http) {
final String prefix = http ? "https://conversations.im/i/" : "xmpp:"; final String prefix = http ? "https://conversations.im/i/" : "xmpp:";
if (contact != null) { if (contact != null) {
return prefix+contact.getJid().toBareJid().toString(); return prefix+contact.getJid().asBareJid().toString();
} else { } else {
return ""; return "";
} }
@ -180,12 +179,12 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
showInactiveOmemo = savedInstanceState != null && savedInstanceState.getBoolean("show_inactive_omemo",false); showInactiveOmemo = savedInstanceState != null && savedInstanceState.getBoolean("show_inactive_omemo",false);
if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) { if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
try { try {
this.accountJid = Jid.fromString(getIntent().getExtras().getString(EXTRA_ACCOUNT)); this.accountJid = Jid.of(getIntent().getExtras().getString(EXTRA_ACCOUNT));
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
} }
try { try {
this.contactJid = Jid.fromString(getIntent().getExtras().getString("contact")); this.contactJid = Jid.of(getIntent().getExtras().getString("contact"));
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
} }
} }
this.messageFingerprint = getIntent().getStringExtra("fingerprint"); this.messageFingerprint = getIntent().getStringExtra("fingerprint");
@ -395,9 +394,9 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
} }
String account; String account;
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
account = contact.getAccount().getJid().getLocalpart(); account = contact.getAccount().getJid().getLocal();
} else { } else {
account = contact.getAccount().getJid().toBareJid().toString(); account = contact.getAccount().getJid().asBareJid().toString();
} }
binding.detailsAccount.setText(getString(R.string.using_account, account)); binding.detailsAccount.setText(getString(R.string.using_account, account));
binding.detailsContactBadge.setImageBitmap(avatarService().get(contact, getPixel(72))); binding.detailsContactBadge.setImageBitmap(avatarService().get(contact, getPixel(72)));
@ -494,7 +493,7 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
@Override @Override
protected void processFingerprintVerification(XmppUri uri) { protected void processFingerprintVerification(XmppUri uri) {
if (contact != null && contact.getJid().toBareJid().equals(uri.getJid()) && uri.hasFingerprints()) { if (contact != null && contact.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(contact,uri.getFingerprints())) { if (xmppConnectionService.verifyFingerprints(contact,uri.getFingerprints())) {
Toast.makeText(this,R.string.verified_fingerprints,Toast.LENGTH_SHORT).show(); Toast.makeText(this,R.string.verified_fingerprints,Toast.LENGTH_SHORT).show();
} }

View File

@ -176,7 +176,7 @@ public class ConversationActivity extends XmppActivity implements OnConversation
Intent intent; Intent intent;
if (pendingAccount != null) { if (pendingAccount != null) {
intent = new Intent(this, EditAccountActivity.class); intent = new Intent(this, EditAccountActivity.class);
intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString()); intent.putExtra("jid", pendingAccount.getJid().asBareJid().toString());
} else { } else {
if (xmppConnectionService.getAccounts().size() == 0) { if (xmppConnectionService.getAccounts().size() == 0) {
if (Config.X509_VERIFICATION) { if (Config.X509_VERIFICATION) {

View File

@ -99,8 +99,7 @@ import eu.siacs.conversations.utils.TimeframeUtils;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT; import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION; import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
@ -671,7 +670,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
contacts[i] = targets.get(i).toString(); contacts[i] = targets.get(i).toString();
} }
intent.putExtra("contacts", contacts); intent.putExtra("contacts", contacts);
intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
intent.putExtra("choice", attachmentChoice); intent.putExtra("choice", attachmentChoice);
intent.putExtra("conversation", conversation.getUuid()); intent.putExtra("conversation", conversation.getUuid());
startActivityForResult(intent, requestCode); startActivityForResult(intent, requestCode);
@ -688,7 +687,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} else if (multi && conversation.getNextCounterpart() != null) { } else if (multi && conversation.getNextCounterpart() != null) {
this.binding.textinput.setHint(getString( this.binding.textinput.setHint(getString(
R.string.send_private_message_to, R.string.send_private_message_to,
conversation.getNextCounterpart().getResourcepart())); conversation.getNextCounterpart().getResource()));
} else if (multi && !conversation.getMucOptions().participating()) { } else if (multi && !conversation.getMucOptions().participating()) {
this.binding.textinput.setHint(R.string.you_are_not_participating); this.binding.textinput.setHint(R.string.you_are_not_participating);
} else { } else {
@ -867,9 +866,9 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
Jid user = message.getCounterpart(); Jid user = message.getCounterpart();
if (user != null && !user.isBareJid()) { if (user != null && !user.isBareJid()) {
if (!message.getConversation().getMucOptions().isUserInRoom(user)) { if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
} }
highlightInConference(user.getResourcepart()); highlightInConference(user.getResource());
} }
return; return;
} else { } else {
@ -888,7 +887,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
Account account = message.getConversation().getAccount(); Account account = message.getConversation().getAccount();
Intent intent = new Intent(activity, EditAccountActivity.class); Intent intent = new Intent(activity, EditAccountActivity.class);
intent.putExtra("jid", account.getJid().toBareJid().toString()); intent.putExtra("jid", account.getJid().asBareJid().toString());
String fingerprint; String fingerprint;
if (message.getEncryption() == Message.ENCRYPTION_PGP if (message.getEncryption() == Message.ENCRYPTION_PGP
|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) { || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
@ -912,7 +911,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (mucOptions.isUserInRoom(user)) { if (mucOptions.isUserInRoom(user)) {
privateMessageWith(user); privateMessageWith(user);
} else { } else {
Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
} }
} }
} }
@ -1853,9 +1852,9 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (pm) { if (pm) {
Jid jid = conversation.getJid(); Jid jid = conversation.getJid();
try { try {
Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick); Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
privateMessageWith(next); privateMessageWith(next);
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
//do nothing //do nothing
} }
} else { } else {
@ -1872,7 +1871,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
private boolean showBlockSubmenu(View view) { private boolean showBlockSubmenu(View view) {
final Jid jid = conversation.getJid(); final Jid jid = conversation.getJid();
if (jid.isDomainJid()) { if (jid.getLocal() == null) {
BlockContactDialog.show(activity, conversation); BlockContactDialog.show(activity, conversation);
} else { } else {
PopupMenu popupMenu = new PopupMenu(getActivity(), view); PopupMenu popupMenu = new PopupMenu(getActivity(), view);
@ -1881,7 +1880,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
Blockable blockable; Blockable blockable;
switch (menuItem.getItemId()) { switch (menuItem.getItemId()) {
case R.id.block_domain: case R.id.block_domain:
blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid()); blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
break; break;
default: default:
blockable = conversation; blockable = conversation;

View File

@ -75,9 +75,8 @@ import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.XmppConnection.Features; import eu.siacs.conversations.xmpp.XmppConnection.Features;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import rocks.xmpp.addr.Jid;
public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist, public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched { OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
@ -179,11 +178,11 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
final Jid jid; final Jid jid;
try { try {
if (mUsernameMode) { if (mUsernameMode) {
jid = Jid.fromParts(binding.accountJid.getText().toString(), getUserModeDomain(), null); jid = Jid.of(binding.accountJid.getText().toString(), getUserModeDomain(), null);
} else { } else {
jid = Jid.fromString(binding.accountJid.getText().toString()); jid = Jid.of(binding.accountJid.getText().toString());
} }
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
if (mUsernameMode) { if (mUsernameMode) {
mAccountJidLayout.setError(getString(R.string.invalid_username)); mAccountJidLayout.setError(getString(R.string.invalid_username));
} else { } else {
@ -221,7 +220,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} }
} }
if (jid.isDomainJid()) { if (jid.getLocal() == null) {
if (mUsernameMode) { if (mUsernameMode) {
mAccountJidLayout.setError(getString(R.string.invalid_username)); mAccountJidLayout.setError(getString(R.string.invalid_username));
} else { } else {
@ -252,7 +251,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
binding.accountJid.requestFocus(); binding.accountJid.requestFocus();
return; return;
} }
mAccount = new Account(jid.toBareJid(), password); mAccount = new Account(jid.asBareJid(), password);
mAccount.setPort(numericPort); mAccount.setPort(numericPort);
mAccount.setHostname(hostname); mAccount.setHostname(hostname);
mAccount.setOption(Account.OPTION_USETLS, true); mAccount.setOption(Account.OPTION_USETLS, true);
@ -396,7 +395,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
public void onClick(final View view) { public void onClick(final View view) {
if (mAccount != null) { if (mAccount != null) {
final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class); final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
startActivity(intent); startActivity(intent);
} }
} }
@ -415,7 +414,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} }
} else { } else {
intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class); intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
intent.putExtra("setup", true); intent.putExtra("setup", true);
} }
if (wasFirstAccount) { if (wasFirstAccount) {
@ -450,7 +449,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) { protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
if (mAccount != null && mAccount.getJid().toBareJid().equals(uri.getJid()) && uri.hasFingerprints()) { if (mAccount != null && mAccount.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) { if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
} }
@ -517,9 +516,9 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
protected boolean jidEdited() { protected boolean jidEdited() {
final String unmodified; final String unmodified;
if (mUsernameMode) { if (mUsernameMode) {
unmodified = this.mAccount.getJid().getLocalpart(); unmodified = this.mAccount.getJid().getLocal();
} else { } else {
unmodified = this.mAccount.getJid().toBareJid().toString(); unmodified = this.mAccount.getJid().asBareJid().toString();
} }
return !unmodified.equals(this.binding.accountJid.getText().toString()); return !unmodified.equals(this.binding.accountJid.getText().toString());
} }
@ -668,8 +667,8 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
recreate(); recreate();
} else if (getIntent() != null) { } else if (getIntent() != null) {
try { try {
this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid")); this.jidToEdit = Jid.of(getIntent().getStringExtra("jid"));
} catch (final InvalidJidException | NullPointerException ignored) { } catch (final IllegalArgumentException | NullPointerException ignored) {
this.jidToEdit = null; this.jidToEdit = null;
} }
if (jidToEdit != null && getIntent().getData() != null) { if (jidToEdit != null && getIntent().getData() != null) {
@ -721,7 +720,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
@Override @Override
public void onSaveInstanceState(final Bundle savedInstanceState) { public void onSaveInstanceState(final Bundle savedInstanceState) {
if (mAccount != null) { if (mAccount != null) {
savedInstanceState.putString("account", mAccount.getJid().toBareJid().toString()); savedInstanceState.putString("account", mAccount.getJid().asBareJid().toString());
savedInstanceState.putBoolean("initMode", mInitMode); savedInstanceState.putBoolean("initMode", mInitMode);
savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE); savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE);
} }
@ -732,10 +731,10 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
boolean init = true; boolean init = true;
if (mSavedInstanceAccount != null) { if (mSavedInstanceAccount != null) {
try { try {
this.mAccount = xmppConnectionService.findAccountByJid(Jid.fromString(mSavedInstanceAccount)); this.mAccount = xmppConnectionService.findAccountByJid(Jid.of(mSavedInstanceAccount));
this.mInitMode = mSavedInstanceInit; this.mInitMode = mSavedInstanceInit;
init = false; init = false;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
this.mAccount = null; this.mAccount = null;
} }
@ -783,7 +782,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
private String getUserModeDomain() { private String getUserModeDomain() {
if (mAccount != null) { if (mAccount != null) {
return mAccount.getJid().getDomainpart(); return mAccount.getJid().getDomain();
} else { } else {
return Config.DOMAIN_LOCK; return Config.DOMAIN_LOCK;
} }
@ -948,9 +947,9 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
if (init) { if (init) {
this.binding.accountJid.getEditableText().clear(); this.binding.accountJid.getEditableText().clear();
if (mUsernameMode) { if (mUsernameMode) {
this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocalpart()); this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocal());
} else { } else {
this.binding.accountJid.getEditableText().append(this.mAccount.getJid().toBareJid().toString()); this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toString());
} }
this.mPassword.getEditableText().clear(); this.mPassword.getEditableText().clear();
this.mPassword.getEditableText().append(this.mAccount.getPassword()); this.mPassword.getEditableText().append(this.mAccount.getPassword());

View File

@ -16,8 +16,7 @@ import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.ui.adapter.KnownHostsAdapter; import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
import eu.siacs.conversations.ui.util.DelayedHintHelper; import eu.siacs.conversations.ui.util.DelayedHintHelper;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class EnterJidDialog { public class EnterJidDialog {
public interface OnEnterJidDialogPositiveListener { public interface OnEnterJidDialogPositiveListener {
@ -86,17 +85,17 @@ public class EnterJidDialog {
} }
try { try {
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
accountJid = Jid.fromParts((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null); accountJid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
} else { } else {
accountJid = Jid.fromString((String) spinner.getSelectedItem()); accountJid = Jid.of((String) spinner.getSelectedItem());
} }
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
return; return;
} }
final Jid contactJid; final Jid contactJid;
try { try {
contactJid = Jid.fromString(jid.getText().toString()); contactJid = Jid.of(jid.getText().toString());
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
jid.setError(context.getString(R.string.invalid_jid)); jid.setError(context.getString(R.string.invalid_jid));
return; return;
} }

View File

@ -16,8 +16,7 @@ import java.security.SecureRandom;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class MagicCreateActivity extends XmppActivity implements TextWatcher { public class MagicCreateActivity extends XmppActivity implements TextWatcher {
@ -66,7 +65,7 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
} else { } else {
mUsername.setError(null); mUsername.setError(null);
try { try {
Jid jid = Jid.fromParts(username.toLowerCase(), Config.MAGIC_CREATE_DOMAIN, null); Jid jid = Jid.of(username.toLowerCase(), Config.MAGIC_CREATE_DOMAIN, null);
Account account = xmppConnectionService.findAccountByJid(jid); Account account = xmppConnectionService.findAccountByJid(jid);
if (account == null) { if (account == null) {
account = new Account(jid, createPassword()); account = new Account(jid, createPassword());
@ -76,13 +75,13 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
xmppConnectionService.createAccount(account); xmppConnectionService.createAccount(account);
} }
Intent intent = new Intent(MagicCreateActivity.this, EditAccountActivity.class); Intent intent = new Intent(MagicCreateActivity.this, EditAccountActivity.class);
intent.putExtra("jid", account.getJid().toBareJid().toString()); intent.putExtra("jid", account.getJid().asBareJid().toString());
intent.putExtra("init", true); intent.putExtra("init", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Toast.makeText(MagicCreateActivity.this, R.string.secure_password_generated, Toast.LENGTH_SHORT).show(); Toast.makeText(MagicCreateActivity.this, R.string.secure_password_generated, Toast.LENGTH_SHORT).show();
WelcomeActivity.addInviteUri(intent, getIntent()); WelcomeActivity.addInviteUri(intent, getIntent());
startActivity(intent); startActivity(intent);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
mUsername.setError(getString(R.string.invalid_username)); mUsername.setError(getString(R.string.invalid_username));
mUsername.requestFocus(); mUsername.requestFocus();
} }
@ -114,9 +113,9 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
if (s.toString().trim().length() > 0) { if (s.toString().trim().length() > 0) {
try { try {
mFullJidDisplay.setVisibility(View.VISIBLE); mFullJidDisplay.setVisibility(View.VISIBLE);
Jid jid = Jid.fromParts(s.toString().toLowerCase(), Config.MAGIC_CREATE_DOMAIN, null); Jid jid = Jid.of(s.toString().toLowerCase(), Config.MAGIC_CREATE_DOMAIN, null);
mFullJidDisplay.setText(getString(R.string.your_full_jid_will_be, jid.toString())); mFullJidDisplay.setText(getString(R.string.your_full_jid_will_be, jid.toString()));
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
mFullJidDisplay.setVisibility(View.INVISIBLE); mFullJidDisplay.setVisibility(View.INVISIBLE);
} }

View File

@ -30,8 +30,7 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate; import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
import eu.siacs.conversations.ui.adapter.AccountAdapter; import eu.siacs.conversations.ui.adapter.AccountAdapter;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpApi;
@ -80,8 +79,8 @@ public class ManageAccountActivity extends XmppActivity implements OnAccountUpda
String jid = savedInstanceState.getString(STATE_SELECTED_ACCOUNT); String jid = savedInstanceState.getString(STATE_SELECTED_ACCOUNT);
if (jid != null) { if (jid != null) {
try { try {
this.selectedAccountJid = Jid.fromString(jid); this.selectedAccountJid = Jid.of(jid);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
this.selectedAccountJid = null; this.selectedAccountJid = null;
} }
} }
@ -113,7 +112,7 @@ public class ManageAccountActivity extends XmppActivity implements OnAccountUpda
@Override @Override
public void onSaveInstanceState(final Bundle savedInstanceState) { public void onSaveInstanceState(final Bundle savedInstanceState) {
if (selectedAccount != null) { if (selectedAccount != null) {
savedInstanceState.putString(STATE_SELECTED_ACCOUNT, selectedAccount.getJid().toBareJid().toString()); savedInstanceState.putString(STATE_SELECTED_ACCOUNT, selectedAccount.getJid().asBareJid().toString());
} }
super.onSaveInstanceState(savedInstanceState); super.onSaveInstanceState(savedInstanceState);
} }
@ -133,7 +132,7 @@ public class ManageAccountActivity extends XmppActivity implements OnAccountUpda
menu.findItem(R.id.mgmt_account_announce_pgp).setVisible(false); menu.findItem(R.id.mgmt_account_announce_pgp).setVisible(false);
menu.findItem(R.id.mgmt_account_publish_avatar).setVisible(false); menu.findItem(R.id.mgmt_account_publish_avatar).setVisible(false);
} }
menu.setHeaderTitle(this.selectedAccount.getJid().toBareJid().toString()); menu.setHeaderTitle(this.selectedAccount.getJid().asBareJid().toString());
} }
@Override @Override
@ -388,7 +387,7 @@ public class ManageAccountActivity extends XmppActivity implements OnAccountUpda
@Override @Override
public void onAccountCreated(Account account) { public void onAccountCreated(Account account) {
Intent intent = new Intent(this, EditAccountActivity.class); Intent intent = new Intent(this, EditAccountActivity.class);
intent.putExtra("jid", account.getJid().toBareJid().toString()); intent.putExtra("jid", account.getJid().asBareJid().toString());
intent.putExtra("init", true); intent.putExtra("init", true);
startActivity(intent); startActivity(intent);
} }

View File

@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
@ -36,9 +35,7 @@ import eu.siacs.conversations.services.ExportLogsService;
import eu.siacs.conversations.services.MemorizingTrustManager; import eu.siacs.conversations.services.MemorizingTrustManager;
import eu.siacs.conversations.ui.util.Color; import eu.siacs.conversations.ui.util.Color;
import eu.siacs.conversations.utils.TimeframeUtils; import eu.siacs.conversations.utils.TimeframeUtils;
import eu.siacs.conversations.xmpp.XmppConnection; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
public class SettingsActivity extends XmppActivity implements public class SettingsActivity extends XmppActivity implements
OnSharedPreferenceChangeListener { OnSharedPreferenceChangeListener {
@ -296,7 +293,7 @@ public class SettingsActivity extends XmppActivity implements
final List<CharSequence> accounts = new ArrayList<>(); final List<CharSequence> accounts = new ArrayList<>();
for (Account account : xmppConnectionService.getAccounts()) { for (Account account : xmppConnectionService.getAccounts()) {
if (account.isEnabled()) { if (account.isEnabled()) {
accounts.add(account.getJid().toBareJid().toString()); accounts.add(account.getJid().asBareJid().toString());
} }
} }
final boolean[] checkedItems = new boolean[accounts.size()]; final boolean[] checkedItems = new boolean[accounts.size()];
@ -316,12 +313,12 @@ public class SettingsActivity extends XmppActivity implements
for (int i = 0; i < checkedItems.length; ++i) { for (int i = 0; i < checkedItems.length; ++i) {
if (checkedItems[i]) { if (checkedItems[i]) {
try { try {
Jid jid = Jid.fromString(accounts.get(i).toString()); Jid jid = Jid.of(accounts.get(i).toString());
Account account = xmppConnectionService.findAccountByJid(jid); Account account = xmppConnectionService.findAccountByJid(jid);
if (account != null) { if (account != null) {
account.getAxolotlService().regenerateKeys(true); account.getAxolotlService().regenerateKeys(true);
} }
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
// //
} }

View File

@ -14,8 +14,7 @@ import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.ui.adapter.AccountAdapter; import eu.siacs.conversations.ui.adapter.AccountAdapter;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ShareViaAccountActivity extends XmppActivity { public class ShareViaAccountActivity extends XmppActivity {
public static final String EXTRA_CONTACT = "contact"; public static final String EXTRA_CONTACT = "contact";
@ -57,11 +56,11 @@ public class ShareViaAccountActivity extends XmppActivity {
final String body = getIntent().getStringExtra(EXTRA_BODY); final String body = getIntent().getStringExtra(EXTRA_BODY);
try { try {
final Jid contact = Jid.fromString(getIntent().getStringExtra(EXTRA_CONTACT)); final Jid contact = Jid.of(getIntent().getStringExtra(EXTRA_CONTACT));
final Conversation conversation = xmppConnectionService.findOrCreateConversation( final Conversation conversation = xmppConnectionService.findOrCreateConversation(
account, contact, false, false); account, contact, false, false);
switchToConversation(conversation, body, false); switchToConversation(conversation, body, false);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
// ignore error // ignore error
} }
@ -88,11 +87,11 @@ public class ShareViaAccountActivity extends XmppActivity {
final Account account = xmppConnectionService.getAccounts().get(0); final Account account = xmppConnectionService.getAccounts().get(0);
try { try {
final Jid contact = Jid.fromString(getIntent().getStringExtra(EXTRA_CONTACT)); final Jid contact = Jid.of(getIntent().getStringExtra(EXTRA_CONTACT));
final Conversation conversation = xmppConnectionService.findOrCreateConversation( final Conversation conversation = xmppConnectionService.findOrCreateConversation(
account, contact, false, false); account, contact, false, false);
switchToConversation(conversation, body, false); switchToConversation(conversation, body, false);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
// ignore error // ignore error
} }

View File

@ -31,8 +31,7 @@ import eu.siacs.conversations.ui.adapter.ConversationAdapter;
import eu.siacs.conversations.ui.service.EmojiService; import eu.siacs.conversations.ui.service.EmojiService;
import eu.siacs.conversations.ui.util.PresenceSelector; import eu.siacs.conversations.ui.util.PresenceSelector;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ShareWithActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate { public class ShareWithActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate {
@ -266,8 +265,8 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
}else{ }else{
Account account; Account account;
try { try {
account = xmppConnectionService.findAccountByJid(Jid.fromString(share.account)); account = xmppConnectionService.findAccountByJid(Jid.of(share.account));
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
account = null; account = null;
} }
if (account == null) { if (account == null) {
@ -276,8 +275,8 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
try { try {
conversation = xmppConnectionService conversation = xmppConnectionService
.findOrCreateConversation(account, Jid.fromString(share.contact), false,true); .findOrCreateConversation(account, Jid.of(share.contact), false,true);
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
return; return;
} }
} }

View File

@ -80,8 +80,7 @@ import eu.siacs.conversations.ui.util.DelayedHintHelper;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class StartConversationActivity extends XmppActivity implements OnRosterUpdate, OnUpdateBlocklist { public class StartConversationActivity extends XmppActivity implements OnRosterUpdate, OnUpdateBlocklist {
@ -271,12 +270,12 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null; String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
if (searchString != null && !searchString.trim().isEmpty()) { if (searchString != null && !searchString.trim().isEmpty()) {
try { try {
Jid jid = Jid.fromString(searchString); Jid jid = Jid.of(searchString);
if (!jid.isDomainJid() && jid.isBareJid() && jid.getDomainpart().contains(".")) { if (jid.getLocal() != null && jid.isBareJid() && jid.getDomain().contains(".")) {
showCreateContactDialog(jid.toString(),null); showCreateContactDialog(jid.toString(),null);
return; return;
} }
} catch (InvalidJidException ignored) { } catch (IllegalArgumentException ignored) {
//ignore and fall through //ignore and fall through
} }
} }
@ -369,7 +368,7 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
Bookmark bookmark = (Bookmark) conferences.get(position); Bookmark bookmark = (Bookmark) conferences.get(position);
Intent shareIntent = new Intent(); Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().toBareJid().toString() + "?join"); shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().asBareJid().toString() + "?join");
shareIntent.setType("text/plain"); shareIntent.setType("text/plain");
try { try {
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with))); startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
@ -518,8 +517,8 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
} }
final Jid conferenceJid; final Jid conferenceJid;
try { try {
conferenceJid = Jid.fromString(jid.getText().toString()); conferenceJid = Jid.of(jid.getText().toString());
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
jid.setError(getString(R.string.invalid_jid)); jid.setError(getString(R.string.invalid_jid));
return; return;
} }
@ -528,9 +527,9 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
if (account.hasBookmarkFor(conferenceJid)) { if (account.hasBookmarkFor(conferenceJid)) {
jid.setError(getString(R.string.bookmark_already_exists)); jid.setError(getString(R.string.bookmark_already_exists));
} else { } else {
final Bookmark bookmark = new Bookmark(account, conferenceJid.toBareJid()); final Bookmark bookmark = new Bookmark(account, conferenceJid.asBareJid());
bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))); bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
String nick = conferenceJid.getResourcepart(); String nick = conferenceJid.getResource();
if (nick != null && !nick.isEmpty()) { if (nick != null && !nick.isEmpty()) {
bookmark.setNick(nick); bookmark.setNick(nick);
} }
@ -575,7 +574,7 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
intent.putExtra("multiple", true); intent.putExtra("multiple", true);
intent.putExtra("show_enter_jid", true); intent.putExtra("show_enter_jid", true);
intent.putExtra("subject", subject.getText().toString()); intent.putExtra("subject", subject.getText().toString());
intent.putExtra(EXTRA_ACCOUNT, account.getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, account.getJid().asBareJid().toString());
intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants); intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
startActivityForResult(intent, REQUEST_CREATE_CONFERENCE); startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
} }
@ -592,11 +591,11 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
Jid jid; Jid jid;
try { try {
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
jid = Jid.fromParts((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null); jid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
} else { } else {
jid = Jid.fromString((String) spinner.getSelectedItem()); jid = Jid.of((String) spinner.getSelectedItem());
} }
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
return null; return null;
} }
return xmppConnectionService.findAccountByJid(jid); return xmppConnectionService.findAccountByJid(jid);
@ -687,14 +686,14 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
String[] toAdd = intent.getStringArrayExtra("contacts"); String[] toAdd = intent.getStringArrayExtra("contacts");
for (String item : toAdd) { for (String item : toAdd) {
try { try {
jids.add(Jid.fromString(item)); jids.add(Jid.of(item));
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
//ignored //ignored
} }
} }
} else { } else {
try { try {
jids.add(Jid.fromString(intent.getStringExtra("contact"))); jids.add(Jid.of(intent.getStringExtra("contact")));
} catch (Exception e) { } catch (Exception e) {
//ignored //ignored
} }
@ -769,9 +768,9 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
for (Account account : xmppConnectionService.getAccounts()) { for (Account account : xmppConnectionService.getAccounts()) {
if (account.getStatus() != Account.State.DISABLED) { if (account.getStatus() != Account.State.DISABLED) {
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
this.mActivatedAccounts.add(account.getJid().getLocalpart()); this.mActivatedAccounts.add(account.getJid().getLocal());
} else { } else {
this.mActivatedAccounts.add(account.getJid().toBareJid().toString()); this.mActivatedAccounts.add(account.getJid().asBareJid().toString());
} }
} }
} }
@ -839,7 +838,7 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
switchToConversation(muc, invite.getBody(), false); switchToConversation(muc, invite.getBody(), false);
return true; return true;
} else { } else {
showJoinConferenceDialog(invite.getJid().toBareJid().toString()); showJoinConferenceDialog(invite.getJid().asBareJid().toString());
return false; return false;
} }
} else if (contacts.size() == 0) { } else if (contacts.size() == 0) {
@ -880,7 +879,7 @@ public class StartConversationActivity extends XmppActivity implements OnRosterU
View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null); View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
final CheckBox isTrustedSource = (CheckBox) view.findViewById(R.id.trusted_source); final CheckBox isTrustedSource = (CheckBox) view.findViewById(R.id.trusted_source);
TextView warning = (TextView) view.findViewById(R.id.warning); TextView warning = (TextView) view.findViewById(R.id.warning);
String jid = contact.getJid().toBareJid().toString(); String jid = contact.getJid().asBareJid().toString();
SpannableString spannable = new SpannableString(getString(R.string.verifying_omemo_keys_trusted_source, jid, contact.getDisplayName())); SpannableString spannable = new SpannableString(getString(R.string.verifying_omemo_keys_trusted_source, jid, contact.getDisplayName()));
int start = spannable.toString().indexOf(jid); int start = spannable.toString().indexOf(jid);
if (start >= 0) { if (start >= 0) {

View File

@ -37,8 +37,7 @@ import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdated { public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdated {
@ -85,8 +84,8 @@ public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdat
this.contactJids = new ArrayList<>(); this.contactJids = new ArrayList<>();
for(String jid : getIntent().getStringArrayExtra("contacts")) { for(String jid : getIntent().getStringArrayExtra("contacts")) {
try { try {
this.contactJids.add(Jid.fromString(jid)); this.contactJids.add(Jid.of(jid));
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -232,7 +231,7 @@ public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdat
showCameraToast(); showCameraToast();
} }
binding.ownKeysTitle.setText(mAccount.getJid().toBareJid().toString()); binding.ownKeysTitle.setText(mAccount.getJid().asBareJid().toString());
binding.ownKeysCard.setVisibility(hasOwnKeys ? View.VISIBLE : View.GONE); binding.ownKeysCard.setVisibility(hasOwnKeys ? View.VISIBLE : View.GONE);
binding.foreignKeys.setVisibility(hasForeignKeys ? View.VISIBLE : View.GONE); binding.foreignKeys.setVisibility(hasForeignKeys ? View.VISIBLE : View.GONE);
if(hasPendingKeyFetches()) { if(hasPendingKeyFetches()) {

View File

@ -16,7 +16,7 @@ import java.util.List;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.persistance.DatabaseBackend; import eu.siacs.conversations.persistance.DatabaseBackend;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class UriHandlerActivity extends AppCompatActivity { public class UriHandlerActivity extends AppCompatActivity {
@ -102,7 +102,7 @@ public class UriHandlerActivity extends AppCompatActivity {
} else if (accounts.contains(xmppUri.getJid())) { } else if (accounts.contains(xmppUri.getJid())) {
intent = new Intent(getApplicationContext(), EditAccountActivity.class); intent = new Intent(getApplicationContext(), EditAccountActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.putExtra("jid", xmppUri.getJid().toBareJid().toString()); intent.putExtra("jid", xmppUri.getJid().asBareJid().toString());
intent.setData(uri); intent.setData(uri);
} else if (xmppUri.isJidValid()){ } else if (xmppUri.isJidValid()){
intent = new Intent(getApplicationContext(), StartConversationActivity.class); intent = new Intent(getApplicationContext(), StartConversationActivity.class);

View File

@ -67,7 +67,7 @@ public class WelcomeActivity extends XmppActivity {
List<Account> accounts = xmppConnectionService.getAccounts(); List<Account> accounts = xmppConnectionService.getAccounts();
Intent intent = new Intent(WelcomeActivity.this, EditAccountActivity.class); Intent intent = new Intent(WelcomeActivity.this, EditAccountActivity.class);
if (accounts.size() == 1) { if (accounts.size() == 1) {
intent.putExtra("jid", accounts.get(0).getJid().toBareJid().toString()); intent.putExtra("jid", accounts.get(0).getJid().asBareJid().toString());
intent.putExtra("init", true); intent.putExtra("init", true);
} else if (accounts.size() >= 1) { } else if (accounts.size() >= 1) {
intent = new Intent(WelcomeActivity.this, ManageAccountActivity.class); intent = new Intent(WelcomeActivity.this, ManageAccountActivity.class);

View File

@ -71,8 +71,7 @@ import eu.siacs.conversations.ui.util.PresenceSelector;
import eu.siacs.conversations.utils.ExceptionHelper; import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public abstract class XmppActivity extends AppCompatActivity { public abstract class XmppActivity extends AppCompatActivity {
@ -394,8 +393,8 @@ public abstract class XmppActivity extends AppCompatActivity {
} else if (presences.size() == 1) { } else if (presences.size() == 1) {
String presence = presences.toResourceArray()[0]; String presence = presences.toResourceArray()[0];
try { try {
conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence)); conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
conversation.setNextCounterpart(null); conversation.setNextCounterpart(null);
} }
listener.onPresenceSelected(); listener.onPresenceSelected();
@ -527,7 +526,7 @@ public abstract class XmppActivity extends AppCompatActivity {
public void switchToContactDetails(Contact contact, String messageFingerprint) { public void switchToContactDetails(Contact contact, String messageFingerprint) {
Intent intent = new Intent(this, ContactDetailsActivity.class); Intent intent = new Intent(this, ContactDetailsActivity.class);
intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT); intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString()); intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
intent.putExtra("contact", contact.getJid().toString()); intent.putExtra("contact", contact.getJid().toString());
intent.putExtra("fingerprint", messageFingerprint); intent.putExtra("fingerprint", messageFingerprint);
startActivity(intent); startActivity(intent);
@ -539,7 +538,7 @@ public abstract class XmppActivity extends AppCompatActivity {
public void switchToAccount(Account account, boolean init) { public void switchToAccount(Account account, boolean init) {
Intent intent = new Intent(this, EditAccountActivity.class); Intent intent = new Intent(this, EditAccountActivity.class);
intent.putExtra("jid", account.getJid().toBareJid().toString()); intent.putExtra("jid", account.getJid().asBareJid().toString());
intent.putExtra("init", init); intent.putExtra("init", init);
if (init) { if (init) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
@ -879,8 +878,8 @@ public abstract class XmppActivity extends AppCompatActivity {
protected Account extractAccount(Intent intent) { protected Account extractAccount(Intent intent) {
String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null; String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
try { try {
return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null; return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
return null; return null;
} }
} }
@ -935,12 +934,12 @@ public abstract class XmppActivity extends AppCompatActivity {
if (data.getBooleanExtra("multiple", false)) { if (data.getBooleanExtra("multiple", false)) {
String[] toAdd = data.getStringArrayExtra("contacts"); String[] toAdd = data.getStringArrayExtra("contacts");
for (String item : toAdd) { for (String item : toAdd) {
invite.jids.add(Jid.fromString(item)); invite.jids.add(Jid.of(item));
} }
} else { } else {
invite.jids.add(Jid.fromString(data.getStringExtra("contact"))); invite.jids.add(Jid.of(data.getStringExtra("contact")));
} }
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
return null; return null;
} }
return invite; return invite;
@ -958,7 +957,7 @@ public abstract class XmppActivity extends AppCompatActivity {
} }
return false; return false;
} else { } else {
jids.add(conversation.getJid().toBareJid()); jids.add(conversation.getJid().asBareJid());
return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback); return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
} }
} }

View File

@ -54,9 +54,9 @@ public class AccountAdapter extends ArrayAdapter<Account> {
} }
TextView jid = view.findViewById(R.id.account_jid); TextView jid = view.findViewById(R.id.account_jid);
if (Config.DOMAIN_LOCK != null) { if (Config.DOMAIN_LOCK != null) {
jid.setText(account.getJid().getLocalpart()); jid.setText(account.getJid().getLocal());
} else { } else {
jid.setText(account.getJid().toBareJid().toString()); jid.setText(account.getJid().asBareJid().toString());
} }
TextView statusView = view.findViewById(R.id.account_status); TextView statusView = view.findViewById(R.id.account_status);
ImageView imageView = view.findViewById(R.id.account_image); ImageView imageView = view.findViewById(R.id.account_image);
@ -125,7 +125,7 @@ public class AccountAdapter extends ArrayAdapter<Account> {
imageView.setImageBitmap(bm); imageView.setImageBitmap(bm);
imageView.setBackgroundColor(0x00000000); imageView.setBackgroundColor(0x00000000);
} else { } else {
imageView.setBackgroundColor(UIHelper.getColorForName(account.getJid().toBareJid().toString())); imageView.setBackgroundColor(UIHelper.getColorForName(account.getJid().asBareJid().toString()));
imageView.setImageDrawable(null); imageView.setImageDrawable(null);
final BitmapWorkerTask task = new BitmapWorkerTask(imageView); final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(activity.getResources(), null, task); final AsyncDrawable asyncDrawable = new AsyncDrawable(activity.getResources(), null, task);

View File

@ -57,7 +57,7 @@ public class ConversationAdapter extends ArrayAdapter<Conversation> {
if (conversation.getMode() == Conversation.MODE_SINGLE || activity.useSubjectToIdentifyConference()) { if (conversation.getMode() == Conversation.MODE_SINGLE || activity.useSubjectToIdentifyConference()) {
viewHolder.name.setText(EmojiWrapper.transform(conversation.getName())); viewHolder.name.setText(EmojiWrapper.transform(conversation.getName()));
} else { } else {
viewHolder.name.setText(conversation.getJid().toBareJid().toString()); viewHolder.name.setText(conversation.getJid().asBareJid().toString());
} }
Message message = conversation.getLatestMessage(); Message message = conversation.getLatestMessage();

View File

@ -132,7 +132,7 @@ public class ListItemAdapter extends ArrayAdapter<ListItem> {
imageView.setImageBitmap(bm); imageView.setImageBitmap(bm);
imageView.setBackgroundColor(0x00000000); imageView.setBackgroundColor(0x00000000);
} else { } else {
String seed = item.getJid() != null ? item.getJid().toBareJid().toString() : item.getDisplayName(); String seed = item.getJid() != null ? item.getJid().asBareJid().toString() : item.getDisplayName();
imageView.setBackgroundColor(UIHelper.getColorForName(seed)); imageView.setBackgroundColor(UIHelper.getColorForName(seed));
imageView.setImageDrawable(null); imageView.setImageDrawable(null);
final BitmapWorkerTask task = new BitmapWorkerTask(imageView); final BitmapWorkerTask task = new BitmapWorkerTask(imageView);

View File

@ -510,7 +510,7 @@ public class MessageAdapter extends ArrayAdapter<Message> implements CopyTextVie
} else { } else {
final String to; final String to;
if (message.getCounterpart() != null) { if (message.getCounterpart() != null) {
to = message.getCounterpart().getResourcepart(); to = message.getCounterpart().getResource();
} else { } else {
to = ""; to = "";
} }

View File

@ -7,8 +7,7 @@ import java.util.List;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.xmpp.forms.Field; import eu.siacs.conversations.xmpp.forms.Field;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class FormJidSingleFieldWrapper extends FormTextFieldWrapper { public class FormJidSingleFieldWrapper extends FormTextFieldWrapper {
@ -23,8 +22,8 @@ public class FormJidSingleFieldWrapper extends FormTextFieldWrapper {
String value = getValue(); String value = getValue();
if (!value.isEmpty()) { if (!value.isEmpty()) {
try { try {
Jid.fromString(value); Jid.of(value);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
editText.setError(context.getString(R.string.invalid_jid)); editText.setError(context.getString(R.string.invalid_jid));
editText.requestFocus(); editText.requestFocus();
return false; return false;

View File

@ -43,8 +43,7 @@ import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Presences; import eu.siacs.conversations.entities.Presences;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class PresenceSelector { public class PresenceSelector {
@ -89,9 +88,9 @@ public class PresenceSelector {
builder.setNegativeButton(R.string.cancel, null); builder.setNegativeButton(R.string.cancel, null);
builder.setPositiveButton(R.string.ok, (dialog, which) -> { builder.setPositiveButton(R.string.ok, (dialog, which) -> {
try { try {
Jid next = Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), resourceArray[selectedResource.get()]); Jid next = Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), resourceArray[selectedResource.get()]);
conversation.setNextCounterpart(next); conversation.setNextCounterpart(next);
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
conversation.setNextCounterpart(null); conversation.setNextCounterpart(null);
} }
listener.onPresenceSelected(); listener.onPresenceSelected();

View File

@ -32,8 +32,7 @@ import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.http.AesGcmURLStreamHandler; import eu.siacs.conversations.http.AesGcmURLStreamHandler;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public final class CryptoHelper { public final class CryptoHelper {
public static final String FILETRANSFER = "?FILETRANSFERv1:"; public static final String FILETRANSFER = "?FILETRANSFERv1:";
@ -149,7 +148,7 @@ public final class CryptoHelper {
} }
} }
public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, CertificateParsingException { public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
List<String> emails = new ArrayList<>(); List<String> emails = new ArrayList<>();
if (alternativeNames != null) { if (alternativeNames != null) {
@ -166,14 +165,14 @@ public final class CryptoHelper {
} }
String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null; String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
if (emails.size() >= 1) { if (emails.size() >= 1) {
return new Pair<>(Jid.fromString(emails.get(0)), name); return new Pair<>(Jid.of(emails.get(0)), name);
} else if (name != null){ } else if (name != null){
try { try {
Jid jid = Jid.fromString(name); Jid jid = Jid.of(name);
if (jid.isBareJid() && !jid.isDomainJid()) { if (jid.isBareJid() && jid.getLocal() != null) {
return new Pair<>(jid,null); return new Pair<>(jid,null);
} }
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
return null; return null;
} }
} }
@ -225,7 +224,7 @@ public final class CryptoHelper {
} }
public static String getAccountFingerprint(Account account) { public static String getAccountFingerprint(Account account) {
return getFingerprint(account.getJid().toBareJid().toString()); return getFingerprint(account.getJid().asBareJid().toString());
} }
public static String getFingerprint(String value) { public static String getFingerprint(String value) {

View File

@ -27,10 +27,8 @@ import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.ConversationActivity;
import eu.siacs.conversations.ui.XmppActivity; import eu.siacs.conversations.ui.XmppActivity;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ExceptionHelper { public class ExceptionHelper {
@ -103,13 +101,13 @@ public class ExceptionHelper {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
Log.d(Config.LOGTAG, "using account=" Log.d(Config.LOGTAG, "using account="
+ finalAccount.getJid().toBareJid() + finalAccount.getJid().asBareJid()
+ " to send in stack trace"); + " to send in stack trace");
Conversation conversation = null; Conversation conversation = null;
try { try {
conversation = service.findOrCreateConversation(finalAccount, conversation = service.findOrCreateConversation(finalAccount,
Jid.fromString(Config.BUG_REPORTS), false, true); Jid.of(Config.BUG_REPORTS), false, true);
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
} }
Message message = new Message(conversation, report Message message = new Message(conversation, report
.toString(), Message.ENCRYPTION_NONE); .toString(), Message.ENCRYPTION_NONE);

View File

@ -55,7 +55,7 @@ public class GeoHelper {
locationPluginIntent.putExtra("longitude",longitude); locationPluginIntent.putExtra("longitude",longitude);
if (message.getStatus() != Message.STATUS_RECEIVED) { if (message.getStatus() != Message.STATUS_RECEIVED) {
locationPluginIntent.putExtra("jid",conversation.getAccount().getJid().toString()); locationPluginIntent.putExtra("jid",conversation.getAccount().getJid().toString());
locationPluginIntent.putExtra("name",conversation.getAccount().getJid().getLocalpart()); locationPluginIntent.putExtra("name",conversation.getAccount().getJid().getLocal());
} else { } else {
Contact contact = message.getContact(); Contact contact = message.getContact();
if (contact != null) { if (contact != null) {

View File

@ -34,19 +34,19 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class JidHelper { public class JidHelper {
private static List<String> LOCALPART_BLACKLIST = Arrays.asList("xmpp","jabber","me"); private static List<String> LOCALPART_BLACKLIST = Arrays.asList("xmpp","jabber","me");
public static String localPartOrFallback(Jid jid) { public static String localPartOrFallback(Jid jid) {
if (LOCALPART_BLACKLIST.contains(jid.getLocalpart().toLowerCase(Locale.ENGLISH))) { if (LOCALPART_BLACKLIST.contains(jid.getLocal().toLowerCase(Locale.ENGLISH))) {
final String domain = jid.getDomainpart(); final String domain = jid.getDomain();
final int index = domain.lastIndexOf('.'); final int index = domain.lastIndexOf('.');
return index > 1 ? domain.substring(0,index) : domain; return index > 1 ? domain.substring(0,index) : domain;
} else { } else {
return jid.getUnescapedLocalpart(); return jid.getLocal();
} }
} }

View File

@ -5,18 +5,17 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class NickValidityChecker { public class NickValidityChecker {
private static boolean check(final Conversation conversation, final String nick) { private static boolean check(final Conversation conversation, final String nick) {
Jid room = conversation.getJid(); Jid room = conversation.getJid();
try { try {
Jid full = Jid.fromParts(room.getLocalpart(), room.getDomainpart(), nick); Jid full = Jid.of(room.getLocal(), room.getDomain(), nick);
return conversation.hasMessageWithCounterpart(full) return conversation.hasMessageWithCounterpart(full)
|| conversation.getMucOptions().findUserByFullJid(full) != null; || conversation.getMucOptions().findUserByFullJid(full) != null;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
return false; return false;
} }
} }

View File

@ -26,7 +26,7 @@ import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.MucOptions; import eu.siacs.conversations.entities.MucOptions;
import eu.siacs.conversations.entities.Presence; import eu.siacs.conversations.entities.Presence;
import eu.siacs.conversations.entities.Transferable; import eu.siacs.conversations.entities.Transferable;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class UIHelper { public class UIHelper {
@ -470,7 +470,7 @@ public class UIHelper {
return conversation.getMucOptions().getSelf().getName(); return conversation.getMucOptions().getSelf().getName();
} else { } else {
final Jid jid = conversation.getAccount().getJid(); final Jid jid = conversation.getAccount().getJid();
return jid.hasLocalpart() ? jid.getLocalpart() : jid.toDomainJid().toString(); return jid.getLocal() != null ? jid.getLocal() : Jid.ofDomain(jid.getDomain()).toString();
} }
} }
} }
@ -501,7 +501,7 @@ public class UIHelper {
if (counterpart == null) { if (counterpart == null) {
return ""; return "";
} else if (!counterpart.isBareJid()) { } else if (!counterpart.isBareJid()) {
return counterpart.getResourcepart().trim(); return counterpart.getResource().trim();
} else { } else {
return counterpart.toString().trim(); return counterpart.toString().trim();
} }

View File

@ -8,8 +8,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class XmppUri { public class XmppUri {
@ -32,8 +31,8 @@ public class XmppUri {
parse(Uri.parse(uri)); parse(Uri.parse(uri));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
try { try {
jid = Jid.fromString(uri).toBareJid().toString(); jid = Jid.of(uri).asBareJid().toString();
} catch (InvalidJidException e2) { } catch (IllegalArgumentException e2) {
jid = null; jid = null;
} }
} }
@ -61,7 +60,7 @@ public class XmppUri {
if (segments.size() >= 2 && segments.get(1).contains("@")) { if (segments.size() >= 2 && segments.get(1).contains("@")) {
// sample : https://conversations.im/i/foo@bar.com // sample : https://conversations.im/i/foo@bar.com
try { try {
jid = Jid.fromString(segments.get(1)).toString(); jid = Jid.of(segments.get(1)).toString();
} catch (Exception e) { } catch (Exception e) {
jid = null; jid = null;
} }
@ -106,8 +105,8 @@ public class XmppUri {
} }
} else { } else {
try { try {
jid = Jid.fromString(uri.toString()).toBareJid().toString(); jid = Jid.of(uri.toString()).asBareJid().toString();
} catch (final InvalidJidException ignored) { } catch (final IllegalArgumentException ignored) {
jid = null; jid = null;
} }
} }
@ -179,17 +178,17 @@ public class XmppUri {
public Jid getJid() { public Jid getJid() {
try { try {
return this.jid == null ? null :Jid.fromString(this.jid.toLowerCase()); return this.jid == null ? null :Jid.of(this.jid.toLowerCase());
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
return null; return null;
} }
} }
public boolean isJidValid() { public boolean isJidValid() {
try { try {
Jid.fromString(jid); Jid.of(jid);
return true; return true;
} catch (InvalidJidException e) { } catch (IllegalArgumentException e) {
return false; return false;
} }
} }

View File

@ -11,8 +11,7 @@ import java.util.Locale;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.utils.XmlHelper; import eu.siacs.conversations.utils.XmlHelper;
import eu.siacs.conversations.xmpp.jid.InvalidJidException; import rocks.xmpp.addr.Jid;
import eu.siacs.conversations.xmpp.jid.Jid;
public class Element { public class Element {
private final String name; private final String name;
@ -152,8 +151,8 @@ public class Element {
final String jid = this.getAttribute(name); final String jid = this.getAttribute(name);
if (jid != null && !jid.isEmpty()) { if (jid != null && !jid.isEmpty()) {
try { try {
return Jid.fromString(jid); return Jid.of(jid);
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
Log.e(Config.LOGTAG, "could not parse jid " + jid); Log.e(Config.LOGTAG, "could not parse jid " + jid);
return null; return null;
} }

View File

@ -82,8 +82,6 @@ import eu.siacs.conversations.xml.XmlReader;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.forms.Field; import eu.siacs.conversations.xmpp.forms.Field;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived; import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza; import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
@ -97,6 +95,7 @@ import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket; import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
import rocks.xmpp.addr.Jid;
public class XmppConnection implements Runnable { public class XmppConnection implements Runnable {
@ -174,14 +173,14 @@ public class XmppConnection implements Runnable {
public XmppConnection(final Account account, final XmppConnectionService service) { public XmppConnection(final Account account, final XmppConnectionService service) {
this.account = account; this.account = account;
final String tag = account.getJid().toBareJid().toPreppedString(); final String tag = account.getJid().asBareJid().toString();
mXmppConnectionService = service; mXmppConnectionService = service;
} }
protected void changeStatus(final Account.State nextStatus) { protected void changeStatus(final Account.State nextStatus) {
synchronized (this) { synchronized (this) {
if (Thread.currentThread().isInterrupted()) { if (Thread.currentThread().isInterrupted()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
return; return;
} }
if (account.getStatus() != nextStatus) { if (account.getStatus() != nextStatus) {
@ -224,7 +223,7 @@ public class XmppConnection implements Runnable {
if (mXmppConnectionService.areMessagesInitialized()) { if (mXmppConnectionService.areMessagesInitialized()) {
mXmppConnectionService.resetSendingToWaiting(account); mXmppConnectionService.resetSendingToWaiting(account);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting"); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
features.encryptionEnabled = false; features.encryptionEnabled = false;
inSmacksSession = false; inSmacksSession = false;
isBound = false; isBound = false;
@ -244,12 +243,12 @@ public class XmppConnection implements Runnable {
destination = account.getHostname(); destination = account.getHostname();
this.verifiedHostname = destination; this.verifiedHostname = destination;
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": connect to " + destination + " via Tor"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor");
localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort()); localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
try { try {
startXmpp(localSocket); startXmpp(localSocket);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return; return;
} catch (Exception e) { } catch (Exception e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
@ -267,9 +266,9 @@ public class XmppConnection implements Runnable {
localSocket = tlsFactoryVerifier.factory.createSocket(); localSocket = tlsFactoryVerifier.factory.createSocket();
localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000); localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
final SSLSession session = ((SSLSocket) localSocket).getSession(); final SSLSession session = ((SSLSocket) localSocket).getSession();
final String domain = account.getJid().getDomainpart(); final String domain = account.getJid().getDomain();
if (!tlsFactoryVerifier.verifier.verify(domain, this.verifiedHostname, session)) { if (!tlsFactoryVerifier.verifier.verify(domain, this.verifiedHostname, session)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
throw new StateChangingException(Account.State.TLS_ERROR); throw new StateChangingException(Account.State.TLS_ERROR);
} }
} catch (KeyManagementException e) { } catch (KeyManagementException e) {
@ -285,7 +284,7 @@ public class XmppConnection implements Runnable {
try { try {
startXmpp(localSocket); startXmpp(localSocket);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return; return;
} catch (Exception e) { } catch (Exception e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
@ -300,20 +299,20 @@ public class XmppConnection implements Runnable {
try { try {
startXmpp(localSocket); startXmpp(localSocket);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return; return;
} catch (Exception e) { } catch (Exception e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
} }
} else { } else {
final String domain = account.getJid().getDomainpart(); final String domain = account.getJid().getDomain();
List<Resolver.Result> results = Resolver.resolve(account.getJid().getDomainpart()); List<Resolver.Result> results = Resolver.resolve(account.getJid().getDomain());
Resolver.Result storedBackupResult; Resolver.Result storedBackupResult;
if (!Thread.currentThread().isInterrupted()) { if (!Thread.currentThread().isInterrupted()) {
storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain); storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
if (storedBackupResult != null && !results.contains(storedBackupResult)) { if (storedBackupResult != null && !results.contains(storedBackupResult)) {
results.add(storedBackupResult); results.add(storedBackupResult);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": loaded backup resolver result from db: " + storedBackupResult); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
} }
} else { } else {
storedBackupResult = null; storedBackupResult = null;
@ -321,7 +320,7 @@ public class XmppConnection implements Runnable {
for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) { for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
final Resolver.Result result = iterator.next(); final Resolver.Result result = iterator.next();
if (Thread.currentThread().isInterrupted()) { if (Thread.currentThread().isInterrupted()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Thread was interrupted"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
return; return;
} }
try { try {
@ -331,12 +330,12 @@ public class XmppConnection implements Runnable {
final InetSocketAddress addr; final InetSocketAddress addr;
if (result.getIp() != null) { if (result.getIp() != null) {
addr = new InetSocketAddress(result.getIp(), result.getPort()); addr = new InetSocketAddress(result.getIp(), result.getPort());
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": using values from dns " + result.getHostname().toString() + ": using values from dns " + result.getHostname().toString()
+ "/" + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled); + "/" + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
} else { } else {
addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort()); addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": using values from dns " + ": using values from dns "
+ result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled); + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
} }
@ -353,13 +352,13 @@ public class XmppConnection implements Runnable {
} }
SSLSocketHelper.setSecurity((SSLSocket) localSocket); SSLSocketHelper.setSecurity((SSLSocket) localSocket);
SSLSocketHelper.setSNIHost(tlsFactoryVerifier.factory, (SSLSocket) localSocket, account.getServer().getDomainpart()); SSLSocketHelper.setSNIHost(tlsFactoryVerifier.factory, (SSLSocket) localSocket, account.getServer().getDomain());
SSLSocketHelper.setAlpnProtocol(tlsFactoryVerifier.factory, (SSLSocket) localSocket, "xmpp-client"); SSLSocketHelper.setAlpnProtocol(tlsFactoryVerifier.factory, (SSLSocket) localSocket, "xmpp-client");
localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000); localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), verifiedHostname, ((SSLSocket) localSocket).getSession())) { if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomain(), verifiedHostname, ((SSLSocket) localSocket).getSession())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
if (!iterator.hasNext()) { if (!iterator.hasNext()) {
throw new StateChangingException(Account.State.TLS_ERROR); throw new StateChangingException(Account.State.TLS_ERROR);
} }
@ -376,10 +375,10 @@ public class XmppConnection implements Runnable {
} catch (final StateChangingException e) { } catch (final StateChangingException e) {
throw e; throw e;
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return; return;
} catch (final Throwable e) { } catch (final Throwable e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
if (!iterator.hasNext()) { if (!iterator.hasNext()) {
throw new UnknownHostException(); throw new UnknownHostException();
} }
@ -398,14 +397,14 @@ public class XmppConnection implements Runnable {
} catch (final SocksSocketFactory.SocksProxyNotFoundException e) { } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
this.changeStatus(Account.State.TOR_NOT_AVAILABLE); this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) { } catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage()); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.State.OFFLINE); this.changeStatus(Account.State.OFFLINE);
this.attempt = Math.max(0, this.attempt - 1); this.attempt = Math.max(0, this.attempt - 1);
} finally { } finally {
if (!Thread.currentThread().isInterrupted()) { if (!Thread.currentThread().isInterrupted()) {
forceCloseSocket(); forceCloseSocket();
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": not force closing socket because thread was interrupted"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
} }
} }
} }
@ -442,7 +441,7 @@ public class XmppConnection implements Runnable {
} else { } else {
keyManager = null; keyManager = null;
} }
String domain = account.getJid().getDomainpart(); String domain = account.getJid().getDomain();
sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG()); sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
final SSLSocketFactory factory = sc.getSocketFactory(); final SSLSocketFactory factory = sc.getSocketFactory();
final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive); final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
@ -454,7 +453,7 @@ public class XmppConnection implements Runnable {
synchronized (this) { synchronized (this) {
this.mThread = Thread.currentThread(); this.mThread = Thread.currentThread();
if (this.mThread.isInterrupted()) { if (this.mThread.isInterrupted()) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": aborting connect because thread was interrupted"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
return; return;
} }
forceCloseSocket(); forceCloseSocket();
@ -481,7 +480,7 @@ public class XmppConnection implements Runnable {
Log.e(Config.LOGTAG, String.valueOf(e)); Log.e(Config.LOGTAG, String.valueOf(e));
throw new StateChangingException(Account.State.UNAUTHORIZED); throw new StateChangingException(Account.State.UNAUTHORIZED);
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in"); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
account.setKey(Account.PINNED_MECHANISM_KEY, account.setKey(Account.PINNED_MECHANISM_KEY,
String.valueOf(saslMechanism.getPriority())); String.valueOf(saslMechanism.getPriority()));
tagReader.reset(); tagReader.reset();
@ -531,11 +530,11 @@ public class XmppConnection implements Runnable {
final Element enabled = tagReader.readElement(nextTag); final Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) { if ("true".equals(enabled.getAttribute("resume"))) {
this.streamId = enabled.getAttribute("id"); this.streamId = enabled.getAttribute("id");
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": stream management(" + smVersion + ": stream management(" + smVersion
+ ") enabled (resumable)"); + ") enabled (resumable)");
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": stream management(" + smVersion + ") enabled"); + ": stream management(" + smVersion + ") enabled");
} }
this.stanzasReceived = 0; this.stanzasReceived = 0;
@ -554,11 +553,11 @@ public class XmppConnection implements Runnable {
synchronized (this.mStanzaQueue) { synchronized (this.mStanzaQueue) {
final int serverCount = Integer.parseInt(h); final int serverCount = Integer.parseInt(h);
if (serverCount < stanzasSent) { if (serverCount < stanzasSent) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": session resumed with lost packages"); + ": session resumed with lost packages");
stanzasSent = serverCount; stanzasSent = serverCount;
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed"); Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
} }
acknowledgeStanzaUpTo(serverCount); acknowledgeStanzaUpTo(serverCount);
for (int i = 0; i < this.mStanzaQueue.size(); ++i) { for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
@ -571,7 +570,7 @@ public class XmppConnection implements Runnable {
if (packet instanceof MessagePacket) { if (packet instanceof MessagePacket) {
MessagePacket message = (MessagePacket) packet; MessagePacket message = (MessagePacket) packet;
mXmppConnectionService.markMessage(account, mXmppConnectionService.markMessage(account,
message.getTo().toBareJid(), message.getTo().asBareJid(),
message.getId(), message.getId(),
Message.STATUS_UNSEND); Message.STATUS_UNSEND);
} }
@ -579,12 +578,12 @@ public class XmppConnection implements Runnable {
} }
} catch (final NumberFormatException ignored) { } catch (final NumberFormatException ignored) {
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
changeStatus(Account.State.ONLINE); changeStatus(Account.State.ONLINE);
} else if (nextTag.isStart("r")) { } else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag); tagReader.readElement(nextTag);
if (Config.EXTENDED_SM_LOGGING) { if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
} }
final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion); final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
tagWriter.writeStanzaAsync(ack); tagWriter.writeStanzaAsync(ack);
@ -593,7 +592,7 @@ public class XmppConnection implements Runnable {
synchronized (NotificationService.CATCHUP_LOCK) { synchronized (NotificationService.CATCHUP_LOCK) {
if (mWaitingForSmCatchup.compareAndSet(true, false)) { if (mWaitingForSmCatchup.compareAndSet(true, false)) {
int count = mSmCatchupMessageCounter.get(); int count = mSmCatchupMessageCounter.get();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": SM catchup complete (" + count + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (" + count + ")");
accountUiNeedsRefresh = true; accountUiNeedsRefresh = true;
if (count > 0) { if (count > 0) {
mXmppConnectionService.getNotificationService().finishBacklog(true, account); mXmppConnectionService.getNotificationService().finishBacklog(true, account);
@ -611,18 +610,18 @@ public class XmppConnection implements Runnable {
acknowledgeStanzaUpTo(serverSequence); acknowledgeStanzaUpTo(serverSequence);
} }
} catch (NumberFormatException | NullPointerException e) { } catch (NumberFormatException | NullPointerException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server send ack without sequence number"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
} }
} else if (nextTag.isStart("failed")) { } else if (nextTag.isStart("failed")) {
Element failed = tagReader.readElement(nextTag); Element failed = tagReader.readElement(nextTag);
try { try {
final int serverCount = Integer.parseInt(failed.getAttribute("h")); final int serverCount = Integer.parseInt(failed.getAttribute("h"));
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
synchronized (this.mStanzaQueue) { synchronized (this.mStanzaQueue) {
acknowledgeStanzaUpTo(serverCount); acknowledgeStanzaUpTo(serverCount);
} }
} catch (NumberFormatException | NullPointerException e) { } catch (NumberFormatException | NullPointerException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
} }
resetStreamId(); resetStreamId();
sendBindRequest(); sendBindRequest();
@ -647,7 +646,7 @@ public class XmppConnection implements Runnable {
for (int i = 0; i < mStanzaQueue.size(); ++i) { for (int i = 0; i < mStanzaQueue.size(); ++i) {
if (serverCount >= mStanzaQueue.keyAt(i)) { if (serverCount >= mStanzaQueue.keyAt(i)) {
if (Config.EXTENDED_SM_LOGGING) { if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i)); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
} }
AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i); AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
if (stanza instanceof MessagePacket && acknowledgedListener != null) { if (stanza instanceof MessagePacket && acknowledgedListener != null) {
@ -706,7 +705,7 @@ public class XmppConnection implements Runnable {
if (inSmacksSession) { if (inSmacksSession) {
++stanzasReceived; ++stanzasReceived;
} else if (features.sm()) { } else if (features.sm()) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": not counting stanza("+element.getClass().getSimpleName()+"). Not in smacks session."); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": not counting stanza("+element.getClass().getSimpleName()+"). Not in smacks session.");
} }
lastPacketReceived = SystemClock.elapsedRealtime(); lastPacketReceived = SystemClock.elapsedRealtime();
if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) { if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
@ -737,14 +736,14 @@ public class XmppConnection implements Runnable {
callback = packetCallbackDuple.second; callback = packetCallbackDuple.second;
packetCallbacks.remove(packet.getId()); packetCallbacks.remove(packet.getId());
} else { } else {
Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet"); Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
} }
} else { } else {
if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) { if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
callback = packetCallbackDuple.second; callback = packetCallbackDuple.second;
packetCallbacks.remove(packet.getId()); packetCallbacks.remove(packet.getId());
} else { } else {
Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet"); Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
} }
} }
} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) { } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
@ -795,14 +794,14 @@ public class XmppConnection implements Runnable {
SSLSocketHelper.setSecurity(sslSocket); SSLSocketHelper.setSecurity(sslSocket);
if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), this.verifiedHostname, sslSocket.getSession())) { if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomain(), this.verifiedHostname, sslSocket.getSession())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
throw new StateChangingException(Account.State.TLS_ERROR); throw new StateChangingException(Account.State.TLS_ERROR);
} }
tagReader.setInputStream(sslSocket.getInputStream()); tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream()); tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream(); sendStartStream();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS connection established"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
features.encryptionEnabled = true; features.encryptionEnabled = true;
final Tag tag = tagReader.readTag(); final Tag tag = tagReader.readTag();
if (tag != null && tag.isStart("stream")) { if (tag != null && tag.isStart("stream")) {
@ -812,7 +811,7 @@ public class XmppConnection implements Runnable {
} }
sslSocket.close(); sslSocket.close();
} catch (final NoSuchAlgorithmException | KeyManagementException e1) { } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
throw new StateChangingException(Account.State.TLS_ERROR); throw new StateChangingException(Account.State.TLS_ERROR);
} }
} }
@ -835,7 +834,7 @@ public class XmppConnection implements Runnable {
authenticate(); authenticate();
} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) { } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
if (Config.EXTENDED_SM_LOGGING) { if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resuming after stanza #" + stanzasReceived); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
} }
final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion); final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
this.mSmCatchupMessageCounter.set(0); this.mSmCatchupMessageCounter.set(0);
@ -860,7 +859,7 @@ public class XmppConnection implements Runnable {
saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG()); saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
} else if (mechanisms.contains("SCRAM-SHA-1")) { } else if (mechanisms.contains("SCRAM-SHA-1")) {
saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG()); saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
} else if (mechanisms.contains("PLAIN") && !account.getJid().getDomainpart().equals("nimbuzz.com")) { } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
saslMechanism = new Plain(tagWriter, account); saslMechanism = new Plain(tagWriter, account);
} else if (mechanisms.contains("DIGEST-MD5")) { } else if (mechanisms.contains("DIGEST-MD5")) {
saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG()); saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
@ -917,7 +916,7 @@ public class XmppConnection implements Runnable {
final Element password = new Element("password").setContent(account.getPassword()); final Element password = new Element("password").setContent(account.getPassword());
register.query("jabber:iq:register").addChild(username); register.query("jabber:iq:register").addChild(username);
register.query().addChild(password); register.query().addChild(password);
register.setFrom(account.getJid().toBareJid()); register.setFrom(account.getJid().asBareJid());
sendUnmodifiedIqPacket(register, registrationResponseListener, true); sendUnmodifiedIqPacket(register, registrationResponseListener, true);
} else if (query.hasChild("x", Namespace.DATA)) { } else if (query.hasChild("x", Namespace.DATA)) {
final Data data = Data.parse(query.findChild("x", Namespace.DATA)); final Data data = Data.parse(query.findChild("x", Namespace.DATA));
@ -1005,7 +1004,7 @@ public class XmppConnection implements Runnable {
try { try {
mXmppConnectionService.restoredFromDatabaseLatch.await(); mXmppConnectionService.restoredFromDatabaseLatch.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": interrupted while waiting for DB restore during bind"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": interrupted while waiting for DB restore during bind");
return; return;
} }
clearIqCallbacks(); clearIqCallbacks();
@ -1025,13 +1024,13 @@ public class XmppConnection implements Runnable {
final Element jid = bind.findChild("jid"); final Element jid = bind.findChild("jid");
if (jid != null && jid.getContent() != null) { if (jid != null && jid.getContent() != null) {
try { try {
Jid assignedJid = Jid.fromString(jid.getContent()); Jid assignedJid = Jid.of(jid.getContent());
if (!account.getJid().getDomainpart().equals(assignedJid.getDomainpart())) { if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server tried to re-assign domain to "+assignedJid.getDomainpart()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server tried to re-assign domain to "+assignedJid.getDomain());
throw new StateChangingError(Account.State.BIND_FAILURE); throw new StateChangingError(Account.State.BIND_FAILURE);
} }
if (account.setJid(assignedJid)) { if (account.setJid(assignedJid)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": jid changed during bind. updating database"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
mXmppConnectionService.databaseBackend.updateAccount(account); mXmppConnectionService.databaseBackend.updateAccount(account);
} }
if (streamFeatures.hasChild("session") if (streamFeatures.hasChild("session")
@ -1041,8 +1040,8 @@ public class XmppConnection implements Runnable {
sendPostBindInitialization(); sendPostBindInitialization();
} }
return; return;
} catch (final InvalidJidException e) { } catch (final IllegalArgumentException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
} }
} else { } else {
Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)"); Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
@ -1065,7 +1064,7 @@ public class XmppConnection implements Runnable {
if (this.packetCallbacks.size() == 0) { if (this.packetCallbacks.size() == 0) {
return; return;
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator(); final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Pair<IqPacket, OnIqPacketReceived> entry = iterator.next(); Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
@ -1077,22 +1076,22 @@ public class XmppConnection implements Runnable {
try { try {
callback.onIqPacketReceived(account, failurePacket); callback.onIqPacketReceived(account, failurePacket);
} catch (StateChangingError error) { } catch (StateChangingError error) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
//ignore //ignore
} }
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
} }
public void sendDiscoTimeout() { public void sendDiscoTimeout() {
if (mWaitForDisco.compareAndSet(true, false)) { if (mWaitForDisco.compareAndSet(true, false)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": finalizing bind after disco timeout"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
finalizeBind(); finalizeBind();
} }
} }
private void sendStartSession() { private void sendStartSession() {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending legacy session to outdated server"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET); final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session"); startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
this.sendUnmodifiedIqPacket(startSession, (account, packet) -> { this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
@ -1124,10 +1123,10 @@ public class XmppConnection implements Runnable {
synchronized (this.disco) { synchronized (this.disco) {
this.disco.clear(); this.disco.clear();
} }
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
mPendingServiceDiscoveries.set(0); mPendingServiceDiscoveries.set(0);
if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomainpart())) { if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": do not wait for service discovery"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
mWaitForDisco.set(false); mWaitForDisco.set(false);
} else { } else {
mWaitForDisco.set(true); mWaitForDisco.set(true);
@ -1148,10 +1147,10 @@ public class XmppConnection implements Runnable {
if (discoveryResult == null) { if (discoveryResult == null) {
sendServiceDiscoveryInfo(account.getServer()); sendServiceDiscoveryInfo(account.getServer());
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server caps came from cache"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
disco.put(account.getServer(), discoveryResult); disco.put(account.getServer(), discoveryResult);
} }
sendServiceDiscoveryInfo(account.getJid().toBareJid()); sendServiceDiscoveryInfo(account.getJid().asBareJid());
if (!requestDiscoItemsFirst) { if (!requestDiscoItemsFirst) {
sendServiceDiscoveryItems(account.getServer()); sendServiceDiscoveryItems(account.getServer());
} }
@ -1180,13 +1179,13 @@ public class XmppConnection implements Runnable {
} }
disco.put(jid, result); disco.put(jid, result);
advancedStreamFeaturesLoaded = disco.containsKey(account.getServer()) advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
&& disco.containsKey(account.getJid().toBareJid()); && disco.containsKey(account.getJid().asBareJid());
} }
if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) { if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().asBareJid()))) {
enableAdvancedStreamFeatures(); enableAdvancedStreamFeatures();
} }
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
} }
if (packet.getType() != IqPacket.TYPE.TIMEOUT) { if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
if (mPendingServiceDiscoveries.decrementAndGet() == 0 if (mPendingServiceDiscoveries.decrementAndGet() == 0
@ -1199,7 +1198,7 @@ public class XmppConnection implements Runnable {
} }
private void finalizeBind() { private void finalizeBind() {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
if (bindListener != null) { if (bindListener != null) {
bindListener.onBind(account); bindListener.onBind(account);
} }
@ -1211,7 +1210,7 @@ public class XmppConnection implements Runnable {
sendEnableCarbons(); sendEnableCarbons();
} }
if (getFeatures().blocking() && !features.blockListRequested) { if (getFeatures().blocking() && !features.blockListRequested) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser()); this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
} }
for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) { for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
@ -1222,7 +1221,7 @@ public class XmppConnection implements Runnable {
private void sendServiceDiscoveryItems(final Jid server) { private void sendServiceDiscoveryItems(final Jid server) {
mPendingServiceDiscoveries.incrementAndGet(); mPendingServiceDiscoveries.incrementAndGet();
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET); final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setTo(server.toDomainJid()); iq.setTo(Jid.ofDomain(server.getDomain()));
iq.query("http://jabber.org/protocol/disco#items"); iq.query("http://jabber.org/protocol/disco#items");
this.sendIqPacket(iq, new OnIqPacketReceived() { this.sendIqPacket(iq, new OnIqPacketReceived() {
@ -1243,7 +1242,7 @@ public class XmppConnection implements Runnable {
sendServiceDiscoveryInfo(jid); sendServiceDiscoveryInfo(jid);
} }
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
} }
if (packet.getType() != IqPacket.TYPE.TIMEOUT) { if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
if (mPendingServiceDiscoveries.decrementAndGet() == 0 if (mPendingServiceDiscoveries.decrementAndGet() == 0
@ -1263,11 +1262,11 @@ public class XmppConnection implements Runnable {
@Override @Override
public void onIqPacketReceived(final Account account, final IqPacket packet) { public void onIqPacketReceived(final Account account, final IqPacket packet) {
if (!packet.hasChild("error")) { if (!packet.hasChild("error")) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().asBareJid()
+ ": successfully enabled carbons"); + ": successfully enabled carbons");
features.carbonsEnabled = true; features.carbonsEnabled = true;
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().asBareJid()
+ ": error enableing carbons " + packet.toString()); + ": error enableing carbons " + packet.toString());
} }
} }
@ -1281,14 +1280,14 @@ public class XmppConnection implements Runnable {
} }
if (streamError.hasChild("conflict")) { if (streamError.hasChild("conflict")) {
account.setResource(createNewResource()); account.setResource(createNewResource());
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": switching resource due to conflict (" + account.getResource() + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
throw new IOException(); throw new IOException();
} else if (streamError.hasChild("host-unknown")) { } else if (streamError.hasChild("host-unknown")) {
throw new StateChangingException(Account.State.HOST_UNKNOWN); throw new StateChangingException(Account.State.HOST_UNKNOWN);
} else if (streamError.hasChild("policy-violation")) { } else if (streamError.hasChild("policy-violation")) {
throw new StateChangingException(Account.State.POLICY_VIOLATION); throw new StateChangingException(Account.State.POLICY_VIOLATION);
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": stream error " + streamError.toString()); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
throw new StateChangingException(Account.State.STREAM_ERROR); throw new StateChangingException(Account.State.STREAM_ERROR);
} }
} }
@ -1355,7 +1354,7 @@ public class XmppConnection implements Runnable {
if (force || isBound) { if (force || isBound) {
tagWriter.writeStanzaAsync(packet); tagWriter.writeStanzaAsync(packet);
} else { } else {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+" do not write stanza to unbound stream "+packet.toString()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+" do not write stanza to unbound stream "+packet.toString());
} }
if (packet instanceof AbstractAcknowledgeableStanza) { if (packet instanceof AbstractAcknowledgeableStanza) {
AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet; AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
@ -1371,7 +1370,7 @@ public class XmppConnection implements Runnable {
this.mStanzaQueue.append(stanzasSent, stanza); this.mStanzaQueue.append(stanzasSent, stanza);
if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) { if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
if (Config.EXTENDED_SM_LOGGING) { if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
} }
tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion)); tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
} }
@ -1432,10 +1431,10 @@ public class XmppConnection implements Runnable {
try { try {
socket.close(); socket.close();
} catch (IOException e) { } catch (IOException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception " + e.getMessage() + " during force close"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception " + e.getMessage() + " during force close");
} }
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": socket was null during force close"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": socket was null during force close");
} }
} }
@ -1447,7 +1446,7 @@ public class XmppConnection implements Runnable {
public void disconnect(final boolean force) { public void disconnect(final boolean force) {
interrupt(); interrupt();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force=" + Boolean.toString(force)); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + Boolean.toString(force));
if (force) { if (force) {
forceCloseSocket(); forceCloseSocket();
} else { } else {
@ -1458,19 +1457,19 @@ public class XmppConnection implements Runnable {
final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch; final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
try { try {
currentTagWriter.await(1,TimeUnit.SECONDS); currentTagWriter.await(1,TimeUnit.SECONDS);
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closing stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
currentTagWriter.writeTag(Tag.end("stream:stream")); currentTagWriter.writeTag(Tag.end("stream:stream"));
if (streamCountDownLatch != null) { if (streamCountDownLatch != null) {
if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) { if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote ended stream"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote has not closed socket. force closing"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
} }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": interrupted while gracefully closing stream"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": interrupted while gracefully closing stream");
} catch (final IOException e) { } catch (final IOException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception during disconnect (" + e.getMessage() + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
} finally { } finally {
FileBackend.close(currentSocket); FileBackend.close(currentSocket);
} }
@ -1583,7 +1582,7 @@ public class XmppConnection implements Runnable {
public Identity getServerIdentity() { public Identity getServerIdentity() {
synchronized (this.disco) { synchronized (this.disco) {
ServiceDiscoveryResult result = disco.get(account.getJid().toDomainJid()); ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
if (result == null) { if (result == null) {
return Identity.UNKNOWN; return Identity.UNKNOWN;
} }
@ -1736,38 +1735,38 @@ public class XmppConnection implements Runnable {
public boolean pep() { public boolean pep() {
synchronized (XmppConnection.this.disco) { synchronized (XmppConnection.this.disco) {
ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid()); ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
return info != null && info.hasIdentity("pubsub", "pep"); return info != null && info.hasIdentity("pubsub", "pep");
} }
} }
public boolean pepPersistent() { public boolean pepPersistent() {
synchronized (XmppConnection.this.disco) { synchronized (XmppConnection.this.disco) {
ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid()); ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items"); return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
} }
} }
public boolean pepPublishOptions() { public boolean pepPublishOptions() {
return hasDiscoFeature(account.getJid().toBareJid(),Namespace.PUBSUB_PUBLISH_OPTIONS); return hasDiscoFeature(account.getJid().asBareJid(),Namespace.PUBSUB_PUBLISH_OPTIONS);
} }
public boolean pepOmemoWhitelisted() { public boolean pepOmemoWhitelisted() {
return hasDiscoFeature(account.getJid().toBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED); return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
} }
public boolean mam() { public boolean mam() {
return hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM) return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM)
|| hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY); || hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM_LEGACY);
} }
public boolean mamLegacy() { public boolean mamLegacy() {
return !hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM) return !hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM)
&& hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY); && hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM_LEGACY);
} }
public boolean push() { public boolean push() {
return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0") return hasDiscoFeature(account.getJid().asBareJid(), "urn:xmpp:push:0")
|| hasDiscoFeature(account.getServer(), "urn:xmpp:push:0"); || hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
} }
@ -1790,7 +1789,7 @@ public class XmppConnection implements Runnable {
if (filesize <= maxsize) { if (filesize <= maxsize) {
return true; return true;
} else { } else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
return false; return false;
} }
} catch (Exception e) { } catch (Exception e) {
@ -1816,7 +1815,7 @@ public class XmppConnection implements Runnable {
} }
public boolean stanzaIds() { public boolean stanzaIds() {
return hasDiscoFeature(account.getJid().toBareJid(), Namespace.STANZA_IDS); return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
} }
} }
} }

View File

@ -1,49 +0,0 @@
package eu.siacs.conversations.xmpp.jid;
public class InvalidJidException extends Exception {
// This is probably not the "Java way", but the "Java way" means we'd have a ton of extra tiny,
// annoying classes floating around. I like this.
public final static String INVALID_LENGTH = "JID must be between 0 and 3071 characters";
public final static String INVALID_PART_LENGTH = "JID part must be between 0 and 1023 characters";
public final static String INVALID_CHARACTER = "JID contains an invalid character";
public final static String STRINGPREP_FAIL = "The STRINGPREP operation has failed for the given JID";
public final static String IS_NULL = "JID can not be NULL";
/**
* Constructs a new {@code Exception} that includes the current stack trace.
*/
public InvalidJidException() {
}
/**
* Constructs a new {@code Exception} with the current stack trace and the
* specified detail message.
*
* @param detailMessage the detail message for this exception.
*/
public InvalidJidException(final String detailMessage) {
super(detailMessage);
}
/**
* Constructs a new {@code Exception} with the current stack trace, the
* specified detail message and the specified cause.
*
* @param detailMessage the detail message for this exception.
* @param throwable the cause of this exception.
*/
public InvalidJidException(final String detailMessage, final Throwable throwable) {
super(detailMessage, throwable);
}
/**
* Constructs a new {@code Exception} with the current stack trace and the
* specified cause.
*
* @param throwable the cause of this exception.
*/
public InvalidJidException(final Throwable throwable) {
super(throwable);
}
}

View File

@ -1,243 +0,0 @@
package eu.siacs.conversations.xmpp.jid;
import android.util.LruCache;
import java.net.IDN;
import eu.siacs.conversations.Config;
import gnu.inet.encoding.Stringprep;
import gnu.inet.encoding.StringprepException;
/**
* The `Jid' class provides an immutable representation of a JID.
*/
public final class Jid {
private static LruCache<String,Jid> cache = new LruCache<>(1024);
private final String localpart;
private final String domainpart;
private final String resourcepart;
private static final char[] JID_ESCAPING_CHARS = {' ','"','&','\'','/',':','<','>','@','\\'};
// It's much more efficient to store the full JID as well as the parts instead of figuring them
// all out every time (since some characters are displayed but aren't used for comparisons).
private final String displayjid;
public String getLocalpart() {
return localpart;
}
public String getUnescapedLocalpart() {
if (localpart == null || !localpart.contains("\\")) {
return localpart;
} else {
String localpart = this.localpart;
for(char c : JID_ESCAPING_CHARS) {
localpart = localpart.replace(String.format ("\\%02x", (int)c),String.valueOf(c));
}
return localpart;
}
}
public String getDomainpart() {
return IDN.toUnicode(domainpart);
}
public String getResourcepart() {
return resourcepart;
}
public static Jid fromString(final String jid) throws InvalidJidException {
return Jid.fromString(jid, false);
}
public static Jid fromString(final String jid, final boolean safe) throws InvalidJidException {
return new Jid(jid, safe);
}
public static Jid fromParts(final String localpart,
final String domainpart,
final String resourcepart) throws InvalidJidException {
String out;
if (localpart == null || localpart.isEmpty()) {
out = domainpart;
} else {
out = localpart + "@" + domainpart;
}
if (resourcepart != null && !resourcepart.isEmpty()) {
out = out + "/" + resourcepart;
}
return new Jid(out, false);
}
private Jid(final String jid, final boolean safe) throws InvalidJidException {
if (jid == null) throw new InvalidJidException(InvalidJidException.IS_NULL);
Jid fromCache = Jid.cache.get(jid);
if (fromCache != null) {
displayjid = fromCache.displayjid;
localpart = fromCache.localpart;
domainpart = fromCache.domainpart;
resourcepart = fromCache.resourcepart;
return;
}
// Hackish Android way to count the number of chars in a string... should work everywhere.
final int atCount = jid.length() - jid.replace("@", "").length();
final int slashCount = jid.length() - jid.replace("/", "").length();
// Throw an error if there's anything obvious wrong with the JID...
if (jid.isEmpty() || jid.length() > 3071) {
throw new InvalidJidException(InvalidJidException.INVALID_LENGTH);
}
// Go ahead and check if the localpart or resourcepart is empty.
if (jid.startsWith("@") || (jid.endsWith("@") && slashCount == 0) || jid.startsWith("/") || (jid.endsWith("/") && slashCount < 2)) {
throw new InvalidJidException(InvalidJidException.INVALID_CHARACTER);
}
String finaljid;
final int domainpartStart;
final int atLoc = jid.indexOf("@");
final int slashLoc = jid.indexOf("/");
// If there is no "@" in the JID (eg. "example.net" or "example.net/resource")
// or there are one or more "@" signs but they're all in the resourcepart (eg. "example.net/@/rp@"):
if (atCount == 0 || (atCount > 0 && slashLoc != -1 && atLoc > slashLoc)) {
localpart = "";
finaljid = "";
domainpartStart = 0;
} else {
final String lp = jid.substring(0, atLoc);
try {
localpart = Config.DISABLE_STRING_PREP || safe ? lp : Stringprep.nodeprep(lp);
} catch (final StringprepException e) {
throw new InvalidJidException(InvalidJidException.STRINGPREP_FAIL, e);
}
if (localpart.isEmpty() || localpart.length() > 1023) {
throw new InvalidJidException(InvalidJidException.INVALID_PART_LENGTH);
}
domainpartStart = atLoc + 1;
finaljid = lp + "@";
}
final String dp;
if (slashCount > 0) {
final String rp = jid.substring(slashLoc + 1, jid.length());
try {
resourcepart = Config.DISABLE_STRING_PREP || safe ? rp : Stringprep.resourceprep(rp);
} catch (final StringprepException e) {
throw new InvalidJidException(InvalidJidException.STRINGPREP_FAIL, e);
}
if (resourcepart.isEmpty() || resourcepart.length() > 1023) {
throw new InvalidJidException(InvalidJidException.INVALID_PART_LENGTH);
}
try {
dp = IDN.toUnicode(Stringprep.nameprep(jid.substring(domainpartStart, slashLoc)), IDN.USE_STD3_ASCII_RULES);
} catch (final StringprepException e) {
throw new InvalidJidException(InvalidJidException.STRINGPREP_FAIL, e);
}
finaljid = finaljid + dp + "/" + rp;
} else {
resourcepart = "";
try{
dp = IDN.toUnicode(Stringprep.nameprep(jid.substring(domainpartStart, jid.length())), IDN.USE_STD3_ASCII_RULES);
} catch (final StringprepException e) {
throw new InvalidJidException(InvalidJidException.STRINGPREP_FAIL, e);
}
finaljid = finaljid + dp;
}
// Remove trailing "." before storing the domain part.
if (dp.endsWith(".")) {
try {
domainpart = IDN.toASCII(dp.substring(0, dp.length() - 1), IDN.USE_STD3_ASCII_RULES);
} catch (final IllegalArgumentException e) {
throw new InvalidJidException(e);
}
} else {
try {
domainpart = IDN.toASCII(dp, IDN.USE_STD3_ASCII_RULES);
} catch (final IllegalArgumentException e) {
throw new InvalidJidException(e);
}
}
// TODO: Find a proper domain validation library; validate individual parts, separators, etc.
if (domainpart.isEmpty() || domainpart.length() > 1023) {
throw new InvalidJidException(InvalidJidException.INVALID_PART_LENGTH);
}
Jid.cache.put(jid, this);
this.displayjid = finaljid;
}
public Jid toBareJid() {
try {
return resourcepart.isEmpty() ? this : fromParts(localpart, domainpart, "");
} catch (final InvalidJidException e) {
// This should never happen.
throw new AssertionError("Jid " + this.toString() + " invalid");
}
}
public Jid toDomainJid() {
try {
return resourcepart.isEmpty() && localpart.isEmpty() ? this : fromString(getDomainpart());
} catch (final InvalidJidException e) {
// This should never happen.
throw new AssertionError("Jid " + this.toString() + " invalid");
}
}
@Override
public String toString() {
return displayjid;
}
public String toPreppedString() {
String out;
if (hasLocalpart()) {
out = localpart + '@' + domainpart;
} else {
out = domainpart;
}
if (!resourcepart.isEmpty()) {
out += '/'+resourcepart;
}
return out;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Jid jid = (Jid) o;
return jid.hashCode() == this.hashCode();
}
@Override
public int hashCode() {
int result = localpart.hashCode();
result = 31 * result + domainpart.hashCode();
result = 31 * result + resourcepart.hashCode();
return result;
}
public boolean hasLocalpart() {
return !localpart.isEmpty();
}
public boolean isBareJid() {
return this.resourcepart.isEmpty();
}
public boolean isDomainJid() {
return !this.hasLocalpart();
}
}

View File

@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class JingleCandidate { public class JingleCandidate {

View File

@ -35,11 +35,11 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.stanzas.Content; import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.jingle.stanzas.Reason; import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class JingleConnection implements Transferable { public class JingleConnection implements Transferable {
@ -113,7 +113,7 @@ public class JingleConnection implements Transferable {
public void onFileTransmitted(DownloadableFile file) { public void onFileTransmitted(DownloadableFile file) {
if (responding()) { if (responding()) {
if (expectedHash.length > 0 && !Arrays.equals(expectedHash,file.getSha1Sum())) { if (expectedHash.length > 0 && !Arrays.equals(expectedHash,file.getSha1Sum())) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": hashes did not match"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": hashes did not match");
} }
sendSuccess(); sendSuccess();
mXmppConnectionService.getFileBackend().updateFileParams(message); mXmppConnectionService.getFileBackend().updateFileParams(message);
@ -335,7 +335,7 @@ public class JingleConnection implements Transferable {
private void upgradeNamespace() { private void upgradeNamespace() {
Jid jid = this.message.getCounterpart(); Jid jid = this.message.getCounterpart();
String resource = jid != null ?jid.getResourcepart() : null; String resource = jid != null ?jid.getResource() : null;
if (resource != null) { if (resource != null) {
Presence presence = this.account.getRoster().getContact(jid).getPresences().getPresences().get(resource); Presence presence = this.account.getRoster().getContact(jid).getPresences().getPresences().get(resource);
ServiceDiscoveryResult result = presence != null ? presence.getServiceDiscoveryResult() : null; ServiceDiscoveryResult result = presence != null ? presence.getServiceDiscoveryResult() : null;
@ -354,7 +354,7 @@ public class JingleConnection implements Transferable {
this.mJingleStatus = JINGLE_STATUS_INITIATED; this.mJingleStatus = JINGLE_STATUS_INITIATED;
Conversation conversation = this.mXmppConnectionService Conversation conversation = this.mXmppConnectionService
.findOrCreateConversation(account, .findOrCreateConversation(account,
packet.getFrom().toBareJid(), false, false); packet.getFrom().asBareJid(), false, false);
this.message = new Message(conversation, "", Message.ENCRYPTION_NONE); this.message = new Message(conversation, "", Message.ENCRYPTION_NONE);
this.message.setStatus(Message.STATUS_RECEIVED); this.message.setStatus(Message.STATUS_RECEIVED);
this.mStatus = Transferable.STATUS_OFFER; this.mStatus = Transferable.STATUS_OFFER;
@ -383,7 +383,7 @@ public class JingleConnection implements Transferable {
if (fileOffer != null) { if (fileOffer != null) {
Element encrypted = fileOffer.findChild("encrypted", AxolotlService.PEP_PREFIX); Element encrypted = fileOffer.findChild("encrypted", AxolotlService.PEP_PREFIX);
if (encrypted != null) { if (encrypted != null) {
this.mXmppAxolotlMessage = XmppAxolotlMessage.fromElement(encrypted, packet.getFrom().toBareJid()); this.mXmppAxolotlMessage = XmppAxolotlMessage.fromElement(encrypted, packet.getFrom().asBareJid());
} }
Element fileSize = fileOffer.findChild("size"); Element fileSize = fileOffer.findChild("size");
Element fileNameElement = fileOffer.findChild("name"); Element fileNameElement = fileOffer.findChild("name");
@ -498,7 +498,7 @@ public class JingleConnection implements Transferable {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": other party received offer"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": other party received offer");
if (mJingleStatus == JINGLE_STATUS_OFFERED) { if (mJingleStatus == JINGLE_STATUS_OFFERED) {
mJingleStatus = JINGLE_STATUS_INITIATED; mJingleStatus = JINGLE_STATUS_INITIATED;
mXmppConnectionService.markMessage(message, Message.STATUS_OFFERED); mXmppConnectionService.markMessage(message, Message.STATUS_OFFERED);
@ -680,7 +680,7 @@ public class JingleConnection implements Transferable {
if (connection.getCandidate().isOurs()) { if (connection.getCandidate().isOurs()) {
final String sid; final String sid;
if (ftVersion == Content.Version.FT_3) { if (ftVersion == Content.Version.FT_3) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": use session ID instead of transport ID to activate proxy"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": use session ID instead of transport ID to activate proxy");
sid = getSessionId(); sid = getSessionId();
} else { } else {
sid = getTransportId(); sid = getTransportId();
@ -776,7 +776,7 @@ public class JingleConnection implements Transferable {
} }
private void sendFallbackToIbb() { private void sendFallbackToIbb() {
Log.d(Config.LOGTAG, account.getJid().toBareJid()+": sending fallback to ibb"); Log.d(Config.LOGTAG, account.getJid().asBareJid()+": sending fallback to ibb");
JinglePacket packet = this.bootstrapPacket("transport-replace"); JinglePacket packet = this.bootstrapPacket("transport-replace");
Content content = new Content(this.contentCreator, this.contentName); Content content = new Content(this.contentCreator, this.contentName);
this.transportId = this.mJingleConnectionManager.nextRandomId(); this.transportId = this.mJingleConnectionManager.nextRandomId();
@ -824,7 +824,7 @@ public class JingleConnection implements Transferable {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + " recipient ACKed our transport-accept. creating ibb"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " recipient ACKed our transport-accept. creating ibb");
transport.connect(onIbbTransportConnected); transport.connect(onIbbTransportConnected);
} }
} }
@ -871,7 +871,7 @@ public class JingleConnection implements Transferable {
this.message.setTransferable(null); this.message.setTransferable(null);
this.mJingleConnectionManager.finishConnection(this); this.mJingleConnectionManager.finishConnection(this);
} else { } else {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received session-terminate/success while responding"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": received session-terminate/success while responding");
} }
} }

View File

@ -18,9 +18,9 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class JingleConnectionManager extends AbstractConnectionManager { public class JingleConnectionManager extends AbstractConnectionManager {
private List<JingleConnection> connections = new CopyOnWriteArrayList<>(); private List<JingleConnection> connections = new CopyOnWriteArrayList<>();
@ -87,7 +87,7 @@ public class JingleConnectionManager extends AbstractConnectionManager {
listener.onPrimaryCandidateFound(false, null); listener.onPrimaryCandidateFound(false, null);
return; return;
} }
if (!this.primaryCandidates.containsKey(account.getJid().toBareJid())) { if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS); final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
if (proxy != null) { if (proxy != null) {
IqPacket iq = new IqPacket(IqPacket.TYPE.GET); IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
@ -108,7 +108,7 @@ public class JingleConnectionManager extends AbstractConnectionManager {
candidate.setType(JingleCandidate.TYPE_PROXY); candidate.setType(JingleCandidate.TYPE_PROXY);
candidate.setJid(proxy); candidate.setJid(proxy);
candidate.setPriority(655360 + 65535); candidate.setPriority(655360 + 65535);
primaryCandidates.put(account.getJid().toBareJid(),candidate); primaryCandidates.put(account.getJid().asBareJid(),candidate);
listener.onPrimaryCandidateFound(true,candidate); listener.onPrimaryCandidateFound(true,candidate);
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
listener.onPrimaryCandidateFound(false,null); listener.onPrimaryCandidateFound(false,null);
@ -125,7 +125,7 @@ public class JingleConnectionManager extends AbstractConnectionManager {
} else { } else {
listener.onPrimaryCandidateFound(true, listener.onPrimaryCandidateFound(true,
this.primaryCandidates.get(account.getJid().toBareJid())); this.primaryCandidates.get(account.getJid().asBareJid()));
} }
} }

View File

@ -17,8 +17,8 @@ import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class JingleInbandTransport extends JingleTransport { public class JingleInbandTransport extends JingleTransport {
@ -103,13 +103,13 @@ public class JingleInbandTransport extends JingleTransport {
digest.reset(); digest.reset();
this.fileOutputStream = connection.getFileOutputStream(); this.fileOutputStream = connection.getFileOutputStream();
if (this.fileOutputStream == null) { if (this.fileOutputStream == null) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not create output stream"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": could not create output stream");
callback.onFileTransferAborted(); callback.onFileTransferAborted();
return; return;
} }
this.remainingSize = this.fileSize = file.getExpectedSize(); this.remainingSize = this.fileSize = file.getExpectedSize();
} catch (final NoSuchAlgorithmException | IOException e) { } catch (final NoSuchAlgorithmException | IOException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+" "+e.getMessage()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+" "+e.getMessage());
callback.onFileTransferAborted(); callback.onFileTransferAborted();
} }
} }
@ -126,7 +126,7 @@ public class JingleInbandTransport extends JingleTransport {
this.digest.reset(); this.digest.reset();
fileInputStream = connection.getFileInputStream(); fileInputStream = connection.getFileInputStream();
if (fileInputStream == null) { if (fileInputStream == null) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could no create input stream"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": could no create input stream");
callback.onFileTransferAborted(); callback.onFileTransferAborted();
return; return;
} }
@ -135,7 +135,7 @@ public class JingleInbandTransport extends JingleTransport {
} }
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
callback.onFileTransferAborted(); callback.onFileTransferAborted();
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": "+e.getMessage()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": "+e.getMessage());
} }
} }
@ -196,7 +196,7 @@ public class JingleInbandTransport extends JingleTransport {
fileInputStream.close(); fileInputStream.close();
} }
} catch (IOException e) { } catch (IOException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during sendNextBlock() "+e.getMessage()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": io exception during sendNextBlock() "+e.getMessage());
FileBackend.close(fileInputStream); FileBackend.close(fileInputStream);
this.onFileTransmissionStatusChanged.onFileTransferAborted(); this.onFileTransmissionStatusChanged.onFileTransferAborted();
} }
@ -220,7 +220,7 @@ public class JingleInbandTransport extends JingleTransport {
connection.updateProgress((int) ((((double) (this.fileSize - this.remainingSize)) / this.fileSize) * 100)); connection.updateProgress((int) ((((double) (this.fileSize - this.remainingSize)) / this.fileSize) * 100));
} }
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": "+e.getMessage()); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": "+e.getMessage());
FileBackend.close(fileOutputStream); FileBackend.close(fileOutputStream);
this.onFileTransmissionStatusChanged.onFileTransferAborted(); this.onFileTransmissionStatusChanged.onFileTransferAborted();
} }
@ -246,7 +246,7 @@ public class JingleInbandTransport extends JingleTransport {
this.connected = false; this.connected = false;
this.account.getXmppConnection().sendIqPacket( this.account.getXmppConnection().sendIqPacket(
packet.generateResponse(IqPacket.TYPE.RESULT), null); packet.generateResponse(IqPacket.TYPE.RESULT), null);
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received ibb close"); Log.d(Config.LOGTAG,account.getJid().asBareJid()+": received ibb close");
} else { } else {
Log.d(Config.LOGTAG,payload.toString()); Log.d(Config.LOGTAG,payload.toString());
// TODO some sort of exception // TODO some sort of exception

View File

@ -37,7 +37,7 @@ public class JingleSocks5Transport extends JingleTransport {
MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
StringBuilder destBuilder = new StringBuilder(); StringBuilder destBuilder = new StringBuilder();
if (jingleConnection.getFtVersion() == Content.Version.FT_3) { if (jingleConnection.getFtVersion() == Content.Version.FT_3) {
Log.d(Config.LOGTAG,this.connection.getAccount().getJid().toBareJid()+": using session Id instead of transport Id for proxy destination"); Log.d(Config.LOGTAG,this.connection.getAccount().getJid().asBareJid()+": using session Id instead of transport Id for proxy destination");
destBuilder.append(jingleConnection.getSessionId()); destBuilder.append(jingleConnection.getSessionId());
} else { } else {
destBuilder.append(jingleConnection.getTransportId()); destBuilder.append(jingleConnection.getTransportId());
@ -97,7 +97,7 @@ public class JingleSocks5Transport extends JingleTransport {
digest.reset(); digest.reset();
fileInputStream = connection.getFileInputStream(); fileInputStream = connection.getFileInputStream();
if (fileInputStream == null) { if (fileInputStream == null) {
Log.d(Config.LOGTAG, connection.getAccount().getJid().toBareJid() + ": could not create input stream"); Log.d(Config.LOGTAG, connection.getAccount().getJid().asBareJid() + ": could not create input stream");
callback.onFileTransferAborted(); callback.onFileTransferAborted();
return; return;
} }
@ -117,7 +117,7 @@ public class JingleSocks5Transport extends JingleTransport {
callback.onFileTransmitted(file); callback.onFileTransmitted(file);
} }
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG, connection.getAccount().getJid().toBareJid() + ": "+e.getMessage()); Log.d(Config.LOGTAG, connection.getAccount().getJid().asBareJid() + ": "+e.getMessage());
callback.onFileTransferAborted(); callback.onFileTransferAborted();
} finally { } finally {
FileBackend.close(fileInputStream); FileBackend.close(fileInputStream);
@ -144,7 +144,7 @@ public class JingleSocks5Transport extends JingleTransport {
fileOutputStream = connection.getFileOutputStream(); fileOutputStream = connection.getFileOutputStream();
if (fileOutputStream == null) { if (fileOutputStream == null) {
callback.onFileTransferAborted(); callback.onFileTransferAborted();
Log.d(Config.LOGTAG, connection.getAccount().getJid().toBareJid() + ": could not create output stream"); Log.d(Config.LOGTAG, connection.getAccount().getJid().asBareJid() + ": could not create output stream");
return; return;
} }
double size = file.getExpectedSize(); double size = file.getExpectedSize();
@ -155,7 +155,7 @@ public class JingleSocks5Transport extends JingleTransport {
count = inputStream.read(buffer); count = inputStream.read(buffer);
if (count == -1) { if (count == -1) {
callback.onFileTransferAborted(); callback.onFileTransferAborted();
Log.d(Config.LOGTAG, connection.getAccount().getJid().toBareJid() + ": file ended prematurely with "+remainingSize+" bytes remaining"); Log.d(Config.LOGTAG, connection.getAccount().getJid().asBareJid() + ": file ended prematurely with "+remainingSize+" bytes remaining");
return; return;
} else { } else {
fileOutputStream.write(buffer, 0, count); fileOutputStream.write(buffer, 0, count);
@ -169,7 +169,7 @@ public class JingleSocks5Transport extends JingleTransport {
file.setSha1Sum(digest.digest()); file.setSha1Sum(digest.digest());
callback.onFileTransmitted(file); callback.onFileTransmitted(file);
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG, connection.getAccount().getJid().toBareJid() + ": "+e.getMessage()); Log.d(Config.LOGTAG, connection.getAccount().getJid().asBareJid() + ": "+e.getMessage());
callback.onFileTransferAborted(); callback.onFileTransferAborted();
} finally { } finally {
wakeLock.release(); wakeLock.release();

View File

@ -3,8 +3,8 @@ package eu.siacs.conversations.xmpp.jingle.stanzas;
import android.util.Base64; import android.util.Base64;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import rocks.xmpp.addr.Jid;
public class JinglePacket extends IqPacket { public class JinglePacket extends IqPacket {
Content content = null; Content content = null;

View File

@ -3,7 +3,7 @@ package eu.siacs.conversations.xmpp.pep;
import android.util.Base64; import android.util.Base64;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class Avatar { public class Avatar {

View File

@ -2,7 +2,7 @@ package eu.siacs.conversations.xmpp.stanzas;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jid.Jid; import rocks.xmpp.addr.Jid;
public class AbstractStanza extends Element { public class AbstractStanza extends Element {
@ -33,18 +33,18 @@ public class AbstractStanza extends Element {
public boolean fromServer(final Account account) { public boolean fromServer(final Account account) {
return getFrom() == null return getFrom() == null
|| getFrom().equals(account.getServer()) || getFrom().equals(account.getServer())
|| getFrom().equals(account.getJid().toBareJid()) || getFrom().equals(account.getJid().asBareJid())
|| getFrom().equals(account.getJid()); || getFrom().equals(account.getJid());
} }
public boolean toServer(final Account account) { public boolean toServer(final Account account) {
return getTo() == null return getTo() == null
|| getTo().equals(account.getServer()) || getTo().equals(account.getServer())
|| getTo().equals(account.getJid().toBareJid()) || getTo().equals(account.getJid().asBareJid())
|| getTo().equals(account.getJid()); || getTo().equals(account.getJid());
} }
public boolean fromAccount(final Account account) { public boolean fromAccount(final Account account) {
return getFrom() != null && getFrom().toBareJid().equals(account.getJid().toBareJid()); return getFrom() != null && getFrom().asBareJid().equals(account.getJid().asBareJid());
} }
} }