/** * creates a list of all RosterEntries * @return the rosterEntryArray */ public RosterEntry[] listRoster(){ try{ // get the roster and if it is not loaded reload it Roster roster = Roster.getInstanceFor(connection); if (!roster.isLoaded()) roster.reloadAndWait(); RosterEntry[] result = new RosterEntry[roster.getEntries().size()]; int i = 0; // loop through all roster entries and append them to the array for (RosterEntry entry: roster.getEntries()){ result[i++] = entry; } return result; }catch (Exception e){ e.printStackTrace(); } return new RosterEntry[0]; }
@Override public void run(){ Roster roster = xmppManager.getRoster(); if (roster != null && !roster.isLoaded()) try{ roster.reloadAndWait(); Log.d("SERVICE_DEBUG", "reloaded roster"); }catch (Exception e){ Log.e("SERVICE_ERROR", "Couldn't load the roster"); e.printStackTrace(); } if (roster != null){ Collection<RosterEntry> entries = roster.getEntries(); for (RosterEntry entry : entries) presenceReceived(roster.getPresence(entry.getUser())); roster.addRosterListener(rosterListener); } }
private void rebuildRoster() { Roster roster = Roster.getInstanceFor(mConnection); if (roster == null) { Logger.info(TAG, "no roster, skipping rebuild roster"); return; } Set<RosterEntry> entries = roster.getEntries(); ArrayList<XmppRosterEntry> newRoster = new ArrayList<>(entries.size()); for (RosterEntry entry : entries) { XmppRosterEntry newEntry = getRosterEntryFor(roster, entry); newRoster.add(newEntry); } Collections.sort(newRoster); XmppService.setRosterEntries(newRoster); XmppServiceBroadcastEventEmitter.broadcastRosterChanged(); }
private XmppRosterEntry getRosterEntryFor(Roster roster, RosterEntry entry) { XmppRosterEntry newEntry = new XmppRosterEntry(); newEntry.setXmppJID(entry.getUser()) .setAlias(entry.getName()) .setAvatar(getCachedAvatar(entry.getUser())); if (newEntry.getAvatar() == null) { newEntry.setAvatar(getAvatarFor(entry.getUser())); } Presence presence = roster.getPresence(entry.getUser()); newEntry.setAvailable(presence.isAvailable()) .setPresenceMode(presence.getMode().ordinal()) .setPersonalMessage(presence.getStatus()); newEntry.setUnreadMessages(mMessagesProvider.countUnreadMessages(mAccount.getXmppJid(), entry.getUser())); return newEntry; }
/** * Adds a roster entry to the packet. * * @param rosterEntry a roster entry to add. */ public void addRosterEntry(RosterEntry rosterEntry) { // Obtain a String[] from the roster entry groups name List<String> groupNamesList = new ArrayList<String>(); String[] groupNames; for (RosterGroup group : rosterEntry.getGroups()) { groupNamesList.add(group.getName()); } groupNames = groupNamesList.toArray(new String[groupNamesList.size()]); // Create a new Entry based on the rosterEntry and add it to the packet RemoteRosterEntry remoteRosterEntry = new RemoteRosterEntry(rosterEntry.getUser(), rosterEntry.getName(), groupNames); addRosterEntry(remoteRosterEntry); }
@Override protected void doSetContactName(String address, String name) throws ImException { Contact contact = getContact(address); contact.setName(name); Contact[] contacts = {contact}; notifyContactsPresenceUpdated(contacts); // set name try { RosterEntry entry = mRoster.getEntry(JidCreate.bareFrom(address)); // confirm entry still exists if (entry == null) { return; } entry.setName(name); } catch (Exception e) { throw new ImException(e.toString()); } }
@Override public void entriesUpdated(Collection<Jid> addresses) { final MessageCenterService service = mService.get(); final PresenceListener presenceListener = mPresenceListener.get(); if (service == null || presenceListener == null) return; // we got an updated roster entry // check if it's a subscription "both" for (Jid jid : addresses) { RosterEntry e = service.getRosterEntry(jid.asBareJid()); if (e != null && e.canSeeHisPresence()) { userSubscribed(service, presenceListener, jid); } } }
private void broadcastPresence(Roster roster, RosterEntry entry, BareJid jid, String id) { // this method might be called async final LocalBroadcastManager lbm = mLocalBroadcastManager; if (lbm == null) return; Intent i; // entry present and not pending subscription if (isRosterEntrySubscribed(entry) || Authenticator.isSelfJID(this, jid)) { // roster entry found, look for presence Presence presence = roster.getPresence(jid); i = PresenceListener.createIntent(this, presence, entry); } else { // null type indicates no roster entry found or not authorized i = new Intent(ACTION_PRESENCE); i.putExtra(EXTRA_FROM, jid.toString()); } // to keep track of request-reply i.putExtra(EXTRA_PACKET_ID, id); lbm.sendBroadcast(i); }
public Contact getContact(RosterEntry r) { Contact contact = new Contact(); contact.name = r.getName(); contact.user = r.getUser(); contact.type = r.getType().toString(); Type presenceType = roster.getPresence(r.getUser()).getType(); if (presenceType != null) { contact.presence = presenceType.toString(); } ItemStatus status = r.getStatus(); if (status != null) { contact.status = status.toString(); } // ItemStatus status = r.getStatus(); // null // log.info("roster entry {}", r.toString()); // contact.na= r.getUser(); log.info("getContact {}", contact.toString()); return contact; }
/** * NOTE: on every (re-)connect all entries are added again (loaded), * one method call for all contacts. */ @Override public void entriesAdded(Collection<Jid> addresses) { if (mRoster == null || !mLoaded) return; for (Jid jid: addresses) { RosterEntry entry = mRoster.getEntry(jid.asBareJid()); if (entry == null) { LOGGER.warning("jid not in roster: "+jid); return; } LOGGER.config("entry: "+entry.toString()); mHandler.onEntryAdded(clientToModel(entry)); } }
public boolean removeFromRoster(JID jid) { if (!this.isConnected()) { LOGGER.info("not connected"); return false; } Roster roster = Roster.getInstanceFor(mConn); RosterEntry entry = roster.getEntry(jid.toBareSmack()); if (entry == null) { LOGGER.info("can't find roster entry for jid: "+jid); return true; } try { // blocking roster.removeEntry(entry); } catch (SmackException.NotLoggedInException | SmackException.NoResponseException | XMPPException.XMPPErrorException | SmackException.NotConnectedException | InterruptedException ex) { LOGGER.log(Level.WARNING, "can't remove contact from roster", ex); return false; } return true; }
public void updateRosterEntry(JID jid, String newName) { if (!this.isConnected()) { LOGGER.info("not connected"); return; } Roster roster = Roster.getInstanceFor(mConn); RosterEntry entry = roster.getEntry(jid.toBareSmack()); if (entry == null) { LOGGER.warning("can't find roster entry for jid: "+jid); return; } try { entry.setName(newName); } catch (SmackException.NotConnectedException | SmackException.NoResponseException | XMPPException.XMPPErrorException | InterruptedException ex) { LOGGER.log(Level.WARNING, "can't set name for entry", ex); } }
public void removeAllContacts() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException { Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection()); if (!roster.isLoaded()) { roster.reloadAndWait(); } for (RosterEntry entry : roster.getEntries()) { roster.removeEntry(entry); Presence presence = new Presence(Presence.Type.unsubscribe); presence.setTo(entry.getJid()); XMPPSession.getInstance().sendStanza(presence); } }
public HashMap<Jid, Presence.Type> getContacts() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException { Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection()); if (!roster.isLoaded()) { roster.reloadAndWait(); } String groupName = "Buddies"; RosterGroup group = roster.getGroup(groupName); if (group == null) { roster.createGroup(groupName); group = roster.getGroup(groupName); } HashMap<Jid, Presence.Type> buddies = new HashMap<>(); List<RosterEntry> entries = group.getEntries(); for (RosterEntry entry : entries) { BareJid jid = entry.getJid(); Presence.Type status = roster.getPresence(jid).getType(); buddies.put(jid, status); } return buddies; }
public HashMap<Jid, Presence.Type> getContactsWithSubscriptionPending() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException { Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection()); if (!roster.isLoaded()) { roster.reloadAndWait(); } String groupName = "Buddies"; RosterGroup group = roster.getGroup(groupName); if (group == null) { roster.createGroup(groupName); group = roster.getGroup(groupName); } HashMap<Jid, Presence.Type> buddiesPending = new HashMap<>(); List<RosterEntry> entries = group.getEntries(); for (RosterEntry entry : entries) { if (entry.isSubscriptionPending()) { BareJid jid = entry.getJid(); Presence.Type status = roster.getPresence(jid).getType(); buddiesPending.put(jid, status); } } return buddiesPending; }
@Override public void entriesAdded(Collection<String> collection){ Roster roster = xmppManager.getRoster(); Collection<RosterEntry> entries = roster.getEntries(); for (RosterEntry entry : entries) presenceReceived(roster.getPresence(entry.getUser())); }
@Override public void entriesUpdated(Collection<String> collection){ Roster roster = xmppManager.getRoster(); Collection<RosterEntry> entries = roster.getEntries(); for (RosterEntry entry : entries) presenceReceived(roster.getPresence(entry.getUser())); }
/** * Get online users from roster and store in onlineUsers */ private void getInitialOnlineUsers() { Roster roster = Roster.getInstanceFor(connection); Collection<RosterEntry> entries = roster.getEntries(); if (entries != null && !entries.isEmpty()) { for (RosterEntry entry : entries) { String jid = entry.getUser(); Presence presence = roster.getPresence(jid); if (presence != null) { XMPPError xmppError = presence.getError(); if (xmppError != null) { logger.error(xmppError.getDescriptiveText()); } else { try { if (presence.getType() == Type.available) { onlineUsers.add(jid.substring(0, jid.indexOf('@'))); } else if (presence.getType() == Type.unavailable) { onlineUsers.remove(jid.substring(0, jid.indexOf('@'))); } } catch (Exception e) { logger.error(e.getMessage(), e); } } } } } logger.debug("Online users: {}", onlineUsers.toString()); }
public void removeContact(String remoteAccount) { try { Roster roster = Roster.getInstanceFor(mConnection); RosterEntry entry = roster.getEntry(remoteAccount); roster.removeEntry(entry); clearConversationsWith(remoteAccount); XmppServiceBroadcastEventEmitter.broadcastContactRemoved(remoteAccount); } catch (Exception exc) { Logger.error(TAG, "Error while removing contact: " + remoteAccount, exc); } }
public void renameContact(String remoteAccount, String newAlias) { try { Roster roster = Roster.getInstanceFor(mConnection); RosterEntry entry = roster.getEntry(remoteAccount); entry.setName(newAlias); XmppServiceBroadcastEventEmitter.broadcastContactRenamed(remoteAccount, newAlias); } catch (Exception exc) { Logger.error(TAG, "Error while renaming contact: " + remoteAccount, exc); } }
@Override public void entriesUpdated(Collection<String> addresses) { if (addresses == null || addresses.isEmpty()) { return; } Roster roster = Roster.getInstanceFor(mConnection); if (roster == null) { Logger.info(TAG, "entriesUpdated - No roster instance, skipping rebuild roster"); return; } ArrayList<XmppRosterEntry> entries = getRosterEntries(); if (entries == null || entries.isEmpty()) { Logger.info(TAG, "entriesUpdated - No roster entries. Skipping rebuild roster"); return; } for (String destination : addresses) { destination = getXmppJid(destination); RosterEntry entry = roster.getEntry(destination); XmppRosterEntry xmppRosterEntry = getRosterEntryFor(roster, entry); int index = entries.indexOf(xmppRosterEntry); if (index < 0) { entries.add(xmppRosterEntry); } else { entries.set(index, xmppRosterEntry); } } Collections.sort(entries); XmppServiceBroadcastEventEmitter.broadcastRosterChanged(); }
/** * Sends a roster entry to userID. * * @param rosterEntry the roster entry to send * @param targetUserID the user that will receive the roster entries * @throws NotConnectedException */ public void send(RosterEntry rosterEntry, String targetUserID) throws NotConnectedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); rosterExchange.addRosterEntry(rosterEntry); msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
/** * Sends a roster group to userID. All the entries of the group will be sent to the * target user. * * @param rosterGroup the roster group to send * @param targetUserID the user that will receive the roster entries * @throws NotConnectedException */ public void send(RosterGroup rosterGroup, String targetUserID) throws NotConnectedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); for (RosterEntry entry : rosterGroup.getEntries()) { rosterExchange.addRosterEntry(entry); } msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
/** * Creates a new roster exchange package with the entries specified in roster. * * @param roster the roster to send to other XMPP entity. */ public RosterExchange(Roster roster) { // Add all the roster entries to the new RosterExchange for (RosterEntry rosterEntry : roster.getEntries()) { this.addRosterEntry(rosterEntry); } }
public Map<String, Contact> getContactList() { // Roster roster = Roster.getInstanceFor(connection); Collection<RosterEntry> entries = roster.getEntries(); contacts.clear(); log.info("\n\n" + entries.size() + " buddy(ies):"); for (RosterEntry r : entries) { Contact c = getContact(r); contacts.put(c.user, c); } broadcastState(); return contacts; }
@Override public void onRosterLoaded(Roster roster) { Set<RosterEntry> entries = roster.getEntries(); LOGGER.info("loading "+entries.size()+" entries"); mHandler.onLoaded(entries.stream() .map(KonRosterListener::clientToModel) .collect(Collectors.toList())); mLoaded = true; }
@Override public void entriesUpdated(Collection<Jid> addresses) { // note: we don't know what exactly changed here for (Jid jid: addresses) { RosterEntry entry = mRoster.getEntry(jid.asBareJid()); if (entry == null) { LOGGER.warning("jid not in roster: "+jid); return; } LOGGER.info("entry: "+entry.toString()); mHandler.onEntryUpdate(clientToModel(entry)); } }
public void onAddChatClick(final MenuItem menuItem){ // this button in the optionsMenu will open a dialog containing every // buddy of your roster. That way you can contact each buddy even if you // never had contact with him. String title = getResources().getString(R.string.add_chat_title); // retrieving the roster and saving it in one rosterEntry[] for the full // roster and in one nameList[]. This is seperate in order to ensure // there is a name. If there is no name saved in the roster I will take // the buddyId but without the server and resource part. XmppManager xmppManager = XmppManager.getInstance(); final RosterEntry[] rosterList = xmppManager.listRoster(); final String[] nameList = new String[rosterList.length]; for (int i = 0; i < rosterList.length; i++){ nameList[i] = rosterList[i].getName(); if (nameList[i] == null){ nameList[i] = rosterList[i].getUser(); int index = nameList[i].indexOf('@'); if (index >= 0) nameList[i] = nameList[i].substring(0, index); } } // pretty straight forward setting the title and items and then showing it new AlertDialog.Builder(this) .setTitle(title) .setItems(nameList, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which){ // clicking on one item will open the chatFragment with the // correct buddyId and name. First I save the buddy in the db // and afterwards I retrieve the buddy of the db, because if // the buddy already exists I want to show the name I // previously saved in the db and not the name of the roster // as these are not synced. MessageHistory messageHistory = new MessageHistory (ChatActivity.this); messageHistory.addChat(rosterList[which].getUser(), nameList[which]); onChatOpened(rosterList[which].getUser(), messageHistory .getName(rosterList[which].getUser())); } }).show(); }
@Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // FIXME synchronize this to executor thread if (mConnection == null) return; String address = contact.getAddress().getAddress(); //otherwise, send unsub message and delete from local contact database org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribe); presence.setTo(address); sendPacket(presence); presence = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.unsubscribed); presence.setTo(address); sendPacket(presence); try { RosterEntry entry = mRoster.getEntry(JidCreate.bareFrom(address)); RosterGroup group = mRoster.getGroup(list.getName()); if (entry != null) { if (group == null) { debug(TAG, "could not find group " + list.getName() + " in roster"); if (mRoster != null) mRoster.removeEntry(entry); } else { group.removeEntry(entry); entry = mRoster.getEntry(JidCreate.bareFrom(address)); // Remove from Roster if this is the last group if (entry != null && entry.getGroups().size() <= 1) mRoster.removeEntry(entry); } } } catch (Exception e) { debug(TAG, "remove entry failed: " + e.getMessage()); throw new RuntimeException(e); } notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact); }
@Override public void approveSubscriptionRequest(final Contact contact) { try { BareJid bareJid = JidCreate.bareFrom(contact.getAddress().getBareAddress()); RosterEntry entry = mRoster.getEntry(bareJid); if (entry == null || !entry.canSeeMyPresence()) { org.jivesoftware.smack.packet.Presence response = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribed); response.setTo(bareJid); //send now, or queue if (mConnection != null && mConnection.isAuthenticated()) mConnection.sendStanza(response); else sendPacket(response); } if (entry == null || !entry.canSeeHisPresence()) { org.jivesoftware.smack.packet.Presence request = new org.jivesoftware.smack.packet.Presence( org.jivesoftware.smack.packet.Presence.Type.subscribe); request.setTo(bareJid); //send now, or queue if (mConnection != null && mConnection.isAuthenticated()) mConnection.sendStanza(request); else sendPacket(request); } mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact, mProviderId, mAccountId); ChatSession session = findOrCreateSession(contact.getAddress().toString(), false); if (session != null) session.setSubscribed(true); if (entry != null && entry.canSeeHisPresence()) { requestPresenceRefresh(contact.getAddress().getBareAddress()); qAvatar.put(contact.getAddress().getAddress(),""); if (getOmemo().getManager().contactSupportsOmemo(bareJid)) { getOmemo().getManager().requestDeviceListUpdateFor(bareJid); getOmemo().getManager().buildSessionsWith(bareJid); } } } catch (Exception e) { debug (TAG, "error responding to subscription approval: " + e.getLocalizedMessage()); } }
protected RosterEntry getRosterEntry(Jid jid) { return getRosterEntry(jid.asBareJid()); }
protected RosterEntry getRosterEntry(BareJid jid) { MessageCenterService instance = mInstance.get(); return (instance != null) ? instance.getRosterEntry(jid) : null; }
@CommandHandler(name = ACTION_PRESENCE) private boolean handlePresence(Intent intent, boolean canConnect) { if (canConnect && isConnected()) { final String id = intent.getStringExtra(EXTRA_PACKET_ID); String type = intent.getStringExtra(EXTRA_TYPE); final String to = intent.getStringExtra(EXTRA_TO); if ("probe".equals(type)) { // probing is actually looking into the roster final Roster roster = getRoster(); if (to == null) { for (RosterEntry entry : roster.getEntries()) { broadcastPresence(roster, entry, id); } // broadcast our own presence broadcastMyPresence(id); } else { queueTask(new Runnable() { @Override public void run() { try { broadcastPresence(roster, JidCreate.bareFrom(to), id); } catch (XmppStringprepException e) { Log.w(TAG, "error parsing JID: " + e.getCausingString(), e); // report it because it's a big deal ReportingManager.logException(e); throw new IllegalArgumentException(e); } } }); } } else { // FIXME isn't this somewhat the same as createPresence? String show = intent.getStringExtra(EXTRA_SHOW); Presence p = new Presence(type != null ? Presence.Type.valueOf(type) : Presence.Type.available); p.setStanzaId(id); if (to != null) p.setTo(to); if (intent.hasExtra(EXTRA_PRIORITY)) p.setPriority(intent.getIntExtra(EXTRA_PRIORITY, 0)); String status = intent.getStringExtra(EXTRA_STATUS); if (!TextUtils.isEmpty(status)) p.setStatus(status); if (show != null) p.setMode(Presence.Mode.valueOf(show)); sendPacket(p); } } return false; }
RosterEntry getRosterEntry(BareJid jid) { Roster roster = getRoster(); return (roster != null) ? roster.getEntry(jid) : null; }
private boolean isAuthorized(BareJid jid) { if (Authenticator.isSelfJID(this, jid)) return true; RosterEntry entry = getRosterEntry(jid); return entry != null && isAuthorized(entry); }
private boolean isAuthorized(RosterEntry entry) { return (isRosterEntrySubscribed(entry) || Authenticator.isSelfJID(this, entry.getJid())); }
private boolean isRosterEntrySubscribed(RosterEntry entry) { return (entry != null && (entry.getType() == RosterPacket.ItemType.to || entry.getType() == RosterPacket.ItemType.both) && !entry.isSubscriptionPending()); }
private void broadcastPresence(Roster roster, RosterEntry entry, String id) { broadcastPresence(roster, entry, entry.getJid(), id); }
private boolean isAlreadyTrusted(Presence p) { RosterEntry entry = getRosterEntry(p.getFrom()); return (entry != null && (entry.getType() == RosterPacket.ItemType.to || entry.getType() == RosterPacket.ItemType.both)); }
public static Intent createIntent(Context ctx, Presence p, RosterEntry entry) { Intent i = new Intent(ACTION_PRESENCE); Presence.Type type = p.getType(); i.putExtra(EXTRA_TYPE, type != null ? type.name() : Presence.Type.available.name()); i.putExtra(EXTRA_PACKET_ID, p.getStanzaId()); i.putExtra(EXTRA_FROM, StringUtils.maybeToString(p.getFrom().toString())); i.putExtra(EXTRA_TO, StringUtils.maybeToString(p.getTo())); i.putExtra(EXTRA_STATUS, p.getStatus()); Presence.Mode mode = p.getMode(); i.putExtra(EXTRA_SHOW, mode != null ? mode.name() : Presence.Mode.available.name()); i.putExtra(EXTRA_PRIORITY, p.getPriority()); String jid = p.getFrom().asBareJid().toString(); long timestamp; DelayInformation delay = p.getExtension(DelayInformation.ELEMENT, DelayInformation.NAMESPACE); if (delay != null) { timestamp = delay.getStamp().getTime(); } else { // try last seen from database timestamp = UsersProvider.getLastSeen(ctx, jid); if (timestamp < 0) timestamp = System.currentTimeMillis(); } i.putExtra(EXTRA_STAMP, timestamp); // public key fingerprint String fingerprint = PublicKeyPresence.getFingerprint(p); if (fingerprint == null) { // try untrusted fingerprint from database fingerprint = Keyring.getFingerprint(ctx, jid, MyUsers.Keys.TRUST_UNKNOWN); } i.putExtra(EXTRA_FINGERPRINT, fingerprint); // subscription information if (entry != null) { i.putExtra(EXTRA_ROSTER_NAME, entry.getName()); RosterPacket.ItemType subscriptionType = entry.getType(); i.putExtra(EXTRA_SUBSCRIBED_FROM, subscriptionType == RosterPacket.ItemType.both || subscriptionType == RosterPacket.ItemType.from); i.putExtra(EXTRA_SUBSCRIBED_TO, subscriptionType == RosterPacket.ItemType.both || subscriptionType == RosterPacket.ItemType.to); } return i; }