* @return The action, which was actually performed. This may vary from the specified action, e.g. if you add a contact that already exists, only its groups are updated. If no action was performed, e.g. if you want to delete a contact, that does not exist, null is returned.
* @throws rocks.xmpp.core.stanza.model.StanzaException If the entity returned a stanza error.
* @throws rocks.xmpp.core.session.NoResponseException If the entity did not respond.
*/
public ContactExchange.Item.Action approve(ContactExchange.Item item) throws XmppException {
RosterManager rosterManager = xmppSession.getRosterManager();
Contact contact = rosterManager.getContact(item.getJid());
ContactExchange.Item.Action action = null;
if (item.getAction() == null || item.getAction() == ContactExchange.Item.Action.ADD) {
// If the contact does not exist yes, add it and request subscription.
// (After completing the roster set, the receiving application SHOULD also send a <presence/> stanza of type "subscribe" to the JID of the new item.)
if (contact == null) {
rosterManager.addContact(new Contact(item.getJid(), item.getName(), item.getGroups()), true, null);
action = ContactExchange.Item.Action.ADD;
} else {
List<String> newGroups = new ArrayList<>(contact.getGroups());
List<String> additionalGroups = new ArrayList<>(item.getGroups());
// Remove all existing groups from the list.
additionalGroups.removeAll(newGroups);
if (!additionalGroups.isEmpty()) {
// Then add all additional groups to the existing groups.
newGroups.addAll(additionalGroups);
// ... SHOULD edit the existing item so that will also belong to the specified group (in addition to the existing group, if any).
rosterManager.updateContact(new Contact(contact.getJid(), contact.getName(), newGroups));
action = ContactExchange.Item.Action.MODIFY;
}
}
} else if (item.getAction() == ContactExchange.Item.Action.DELETE) {
if (contact != null) {
List<String> existingGroups = new ArrayList<>(contact.getGroups());
List<String> specifiedGroups = new ArrayList<>(item.getGroups());
// Remove all specified groups from the existing groups.
existingGroups.removeAll(specifiedGroups);
// If there are still some groups left, only update the contact, but do not delete it.
if (!existingGroups.isEmpty()) {
rosterManager.updateContact(new Contact(contact.getJid(), contact.getName(), existingGroups));
action = ContactExchange.Item.Action.MODIFY;
} else {
rosterManager.removeContact(item.getJid());
action = ContactExchange.Item.Action.DELETE;
}
}
} else if (item.getAction() == ContactExchange.Item.Action.MODIFY) {
if (contact != null) {
rosterManager.updateContact(new Contact(item.getJid(), item.getName(), item.getGroups()));
action = ContactExchange.Item.Action.MODIFY;
}
}
return action;
}