private void syncUsers() { for (RosterEntry entry : conn.getRoster().getEntries()) { getBuddyManager() .storeBuddy( new XMPPBuddy( getBuddyManager(), entry.getUser(), entry.getName(), entry.getGroups(), entry)); // Facebook does not support presence probes in their XMPP implementation. See // http://developers.facebook.com/docs/chat#features if (!TransportType.facebook.equals(getTransport().getType())) { // ProbePacket probe = new ProbePacket(this.getJID()+"/"+xmppResource, entry.getUser()); ProbePacket probe = new ProbePacket(null, entry.getUser()); Log.debug("XMPP: Sending the following probe packet: " + probe.toXML()); try { conn.sendPacket(probe); } catch (IllegalStateException e) { Log.debug("XMPP: Not connected while trying to send probe."); } } } try { getTransport().syncLegacyRoster(getJID(), getBuddyManager().getBuddies()); } catch (UserNotFoundException ex) { Log.error("XMPP: User not found while syncing legacy roster: ", ex); } getBuddyManager().activate(); // lets repoll the roster since smack seems to get out of sync... // we'll let the roster listener take care of this though. conn.getRoster().reload(); }
/** * 根据RosterEntry创建一个User * * @param entry * @return */ public User transEntryToUser(RosterEntry entry, Roster roster) { User user = new User(); user.setJID(entry.getUser()); Presence presence = roster.getPresence(entry.getUser()); user.setFrom(presence.getFrom()); user.setStatus(presence.getStatus()); user.setAvailable(presence.isAvailable()); user.setType(entry.getType()); // user.setvCard(userManager.getUserVCard(entry.getUser())); if (entry.getName() == null) { // if(user.getvCard()==null) // user.setName(StringUtil.getUserNameByJid(entry.getUser())); // else { // user.setName(user.getvCard().getNickName()); // } user.setName(StringUtil.getUserNameByJid(entry.getUser())); } else { user.setName(entry.getName()); } String avatar = UserManager.saveAvatar(entry.getUser(), context); user.setAvatar_path(avatar); return user; }
private String getName(RosterEntry rosterEntry) { String name = rosterEntry.getName(); if (name != null && name.length() > 0) { return name; } name = StringUtils.parseName(rosterEntry.getUser()); if (name.length() > 0) { return name; } return rosterEntry.getUser(); }
private ContentValues getContentValuesForRosterEntry(final RosterEntry entry) { final ContentValues values = new ContentValues(); values.put(RosterConstants.JID, entry.getUser()); values.put(RosterConstants.ALIAS, getName(entry)); Presence presence = mRoster.getPresence(entry.getUser()); values.put(RosterConstants.STATUS_MODE, getStatusInt(presence)); values.put(RosterConstants.STATUS_MESSAGE, presence.getStatus()); values.put(RosterConstants.GROUP, getGroup(entry.getGroups())); return values; }
private ContentValues getContentValuesForRosterEntry(final RosterEntry entry) { final ContentValues values = new ContentValues(); values.put(RosterConstants.JID, entry.getUser()); values.put(RosterConstants.ALIAS, getName(entry)); Presence presence = roster.getPresence(entry.getUser()); values.put(RosterConstants.STATUS_MODE, getStatusInt(presence)); if (presence.getType() == Presence.Type.error) { values.put(RosterConstants.STATUS_MESSAGE, presence.getError().toString()); } else values.put(RosterConstants.STATUS_MESSAGE, presence.getStatus()); values.put(RosterConstants.GROUP, getGroup(entry.getGroups())); return values; }
@Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { RosterItem item = (RosterItem) parent.getItemAtPosition(position); String name = item.getName(); String account = item.getAccount(); if (item.isGroup() || item.isAccount()) { if (item.isCollapsed()) { while (service.getCollapsedGroups().contains(name)) service.getCollapsedGroups().remove(name); item.setCollapsed(false); } else { service.getCollapsedGroups().add(name); item.setCollapsed(true); } updateList(); } else if (item.isEntry() || item.isSelf()) { RosterEntry re = item.getEntry(); String jid = re.getUser(); Intent i = new Intent(this, Chat.class); i.putExtra("account", account); i.putExtra("jid", jid); startActivity(i); } else if (item.isMuc()) { Intent i = new Intent(this, Chat.class); i.putExtra("account", account); i.putExtra("jid", item.getName()); startActivity(i); } }
public void buildUserList() { final Collection<RosterEntry> roster = mRoster.getEntries(); for (final RosterEntry rosterEntry : roster) { getUser(rosterEntry.getUser(), true); } transportCheck(); }
public void updateUser(Presence presence) { boolean newUser = true; Contact removeC = null; for (Contact c : contactList) { if (c.getRosterEntry().getUser().equals(StringUtils.parseBareAddress(presence.getFrom()))) { newUser = false; if (!(presence.isAvailable() || presence.isAway())) { removeC = c; } break; } } if (removeC != null) { contactList.remove(removeC); } if (newUser) { RosterEntry re = roster.getEntry(StringUtils.parseBareAddress(presence.getFrom())); Contact c = new Contact(); if (re.getName() == null || re.getName().trim().equals("")) c.setName(re.getUser()); else c.setName(re.getName()); c.setStatus(presence.getStatus()); c.setRosterEntry(re); contactList.add(c); } }
private void xmppRosterPost(XMPPConnection connection) { List<String> jidList = new LinkedList<String>(); System.err.println("INFO: Reading roster."); for (RosterEntry entry : connection.getRoster().getEntries()) { jidList.add(entry.getUser()); System.err.println("INFO: Got " + entry.getUser() + " from roster."); } System.err.println("INFO: Sending " + jidList.size() + " roster entries to server."); BuddylistIQ blIQ = new BuddylistIQ(); blIQ.setFrom(connection.getUser()); blIQ.setTo(this.androidbuddy); blIQ.setBuddies(jidList); blIQ.setIdentity(XMPPUtil.jidWithoutRessource(connection.getUser())); blIQ.setNetwork("roster"); blIQ.setType(IQ.Type.SET); connection.sendPacket(blIQ); }
/** 更改用户状态 */ public void setPresence(int code) { if (connection == null) return; Presence presence; switch (code) { case 0: presence = new Presence(Presence.Type.available); connection.sendPacket(presence); Log.v("state", "设置在线"); break; case 1: presence = new Presence(Presence.Type.available); presence.setMode(Presence.Mode.chat); connection.sendPacket(presence); Log.v("state", "设置Q我吧"); System.out.println(presence.toXML()); break; case 2: presence = new Presence(Presence.Type.available); presence.setMode(Presence.Mode.dnd); connection.sendPacket(presence); Log.v("state", "设置忙碌"); System.out.println(presence.toXML()); break; case 3: presence = new Presence(Presence.Type.available); presence.setMode(Presence.Mode.away); connection.sendPacket(presence); Log.v("state", "设置离开"); System.out.println(presence.toXML()); break; case 4: Roster roster = connection.getRoster(); Collection<RosterEntry> entries = roster.getEntries(); for (RosterEntry entry : entries) { presence = new Presence(Presence.Type.unavailable); presence.setPacketID(Packet.ID_NOT_AVAILABLE); presence.setFrom(connection.getUser()); presence.setTo(entry.getUser()); connection.sendPacket(presence); System.out.println(presence.toXML()); } // 向同一用户的其他客户端发送隐身状态 presence = new Presence(Presence.Type.unavailable); presence.setPacketID(Packet.ID_NOT_AVAILABLE); presence.setFrom(connection.getUser()); presence.setTo(StringUtils.parseBareAddress(connection.getUser())); connection.sendPacket(presence); Log.v("state", "设置隐身"); break; case 5: presence = new Presence(Presence.Type.unavailable); connection.sendPacket(presence); Log.v("state", "设置离线"); break; default: break; } }
static RosterPacket.Item toRosterItem(RosterEntry entry) { RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName()); item.setItemType(entry.getType()); item.setItemStatus(entry.getStatus()); // Set the correct group names for the item. for (RosterGroup group : entry.getGroups()) { item.addGroupName(group.getName()); } return item; }
private String getCurrentJabberID(User user, RosterEntry rosterEntry) { Presence presence = _getPresence(user); String jabberId = null; if (presence != null) { jabberId = presence.getFrom(); } if (jabberId == null) jabberId = rosterEntry.getUser(); if (jabberId == null) jabberId = rosterEntry.getName(); return jabberId; }
public static String toString(RosterEntry entry) { StringBuilder sb = new StringBuilder(); String name = entry.getName(); if (name != null && name.trim().length() > 0) { sb.append(Messages.DeleteContactAction_name_begin_deco) .append(name) .append(Messages.DeleteContactAction_name_end_deco); } sb.append(entry.getUser()); return sb.toString(); }
@Override public List<String> GetUsers() { if (connection == null) return users; Roster roster = connection.getRoster(); Collection<RosterEntry> entries = roster.getEntries(); users = new ArrayList<String>(); for (RosterEntry entry : entries) { users.add(entry.getUser()); System.out.println(entry); } return users; }
public String getNameForEmail(String email) { Log.i("Chat", "Getting name for " + email); if (nameCache.containsKey(email)) { return nameCache.get(email); } else { Roster roster = connection.getRoster(); for (RosterEntry entry : roster.getEntries()) { Log.i("Chat", entry.getUser() + "," + entry.getName()); if (entry.getUser().equals(email)) { String name = entry.getName(); Log.i("Chat", "Got name for " + email + " as " + name); if (name == null || name.equals("")) { return email; } else { nameCache.put(email, name); return name; } } } return email; } }
private void removeOldRosterEntries() { Collection<RosterEntry> rosterEntries = roster.getEntries(); StringBuilder exclusion = new StringBuilder(RosterConstants.JID + " NOT IN ("); boolean first = true; for (RosterEntry rosterEntry : rosterEntries) { updateRosterEntryInDB(rosterEntry); if (first) first = false; else exclusion.append(","); exclusion.append("'").append(rosterEntry.getUser()).append("'"); } exclusion.append(")"); int count = contentResolver.delete(RosterProvider.CONTENT_URI, exclusion.toString(), null); }
private User addJabberUserToUserModelOrUpdateInfo(RosterEntry rosterEntry) { // System.out.println("rosterEntry.getName() = " + rosterEntry.getName()); // System.out.println("rosterEntry.getUser() = " + rosterEntry.getUser()); User user = myUserModel.createUser(getSimpleId(rosterEntry.getUser()), getName()); String newGroup = getUserGroup(rosterEntry); if (newGroup != null) { user.setGroup(newGroup, myUserModel); } user.setDisplayName(rosterEntry.getName(), myUserModel); myUserModel.addUser(user); String jabberId = getCurrentJabberID(user, rosterEntry); updateIsIDEtalkClient(jabberId, user); return user; }
public void runDeleteAction() { RosterEntry rosterEntry = null; List<RosterEntry> selectedRosterEntries = SelectionRetrieverFactory.getSelectionRetriever(RosterEntry.class).getSelection(); if (selectedRosterEntries.size() == 1) { rosterEntry = selectedRosterEntries.get(0); } if (rosterEntry == null) { LOG.error("RosterEntry should not be null at this point!"); // $NON-NLS-1$ return; } if (sessionManager != null) { // Is the chosen user currently in the session? ISarosSession sarosSession = sessionManager.getSarosSession(); String entryJid = rosterEntry.getUser(); if (sarosSession != null) { for (User p : sarosSession.getUsers()) { String pJid = p.getJID().getBase(); // If so, stop the deletion from completing if (entryJid.equals(pJid)) { MessageDialog.openError( null, Messages.DeleteContactAction_error_title, DELETE_ERROR_IN_SESSION); return; } } } } if (MessageDialog.openQuestion( null, Messages.DeleteContactAction_confirm_title, MessageFormat.format( Messages.DeleteContactAction_confirm_message, toString(rosterEntry)))) { try { XMPPUtils.removeFromRoster(connectionService.getConnection(), rosterEntry); } catch (XMPPException e) { LOG.error( "could not delete contact " + toString(rosterEntry) // $NON-NLS-1$ + ":", e); //$NON-NLS-1$ } } }
private void tryToRemoveRosterEntry(String user) throws ClientException { try { RosterEntry rosterEntry = roster.getEntry(user); if (rosterEntry != null) { Presence unsub = new Presence(Presence.Type.unsubscribed); unsub.setTo(rosterEntry.getUser()); extXMPPConnection.sendPacket(unsub); roster.removeEntry(rosterEntry); } } catch (XMPPException e) { throw new ClientException("tryToRemoveRosterEntry", e); } }
private void tryToRemoveRosterEntry(String user) throws YaximXMPPException { try { RosterEntry rosterEntry = mRoster.getEntry(user); if (rosterEntry != null) { // first, unsubscribe the user Presence unsub = new Presence(Presence.Type.unsubscribed); unsub.setTo(rosterEntry.getUser()); mXMPPConnection.sendPacket(unsub); // then, remove from roster mRoster.removeEntry(rosterEntry); } } catch (XMPPException e) { throw new YaximXMPPException("tryToRemoveRosterEntry", e); } }
// TODO: figure out what determines the presence of a RosterEntry's name field public void setActiveChatByName(String name) { Roster roster = connection.getRoster(); String activeUser = null; if (activeChat != null) { activeUser = activeChat.getParticipant(); int index = activeUser.indexOf("/"); // Log.d("Jane", "index: " + index); if (index >= 0) { activeUser = activeUser.substring(0, index); } if (!chatCache.containsKey(activeUser)) { Log.d("Jane", "Caching " + activeUser); chatCache.put(activeUser, activeChat); } } for (RosterEntry entry : roster.getEntries()) { String potentialName = entry.getName(); String email = entry.getUser(); Log.i("Chat", "Checking desired recipient: " + name + " against: " + potentialName); if (potentialName != null && potentialName.regionMatches(true, 0, name, 0, name.length())) { Log.i("Chat", "Setting active chat to " + potentialName + "/" + email); speak("Now talking to " + potentialName); if (chatCache.containsKey(email)) { activeChat = chatCache.get(email); } else { Log.d("Chat", "Chat cache did not contain key " + email); activeChat = connection.getChatManager().createChat(email, null); } return; } else if (email.contains(name)) { // maybe emails will be ok... Log.i("Chat", "Setting active chat to " + email); speak("Now talking to " + email); if (chatCache.containsKey(email)) { activeChat = chatCache.get(email); } else { activeChat = connection.getChatManager().createChat(email, null); } return; } } Log.i("Chat", "No friend matches " + name); speak("Sorry, but I couldn't find a friend named " + name); }
public User setupUser(String uid, boolean addIfNotExists) { final RosterEntry re = mRoster.getEntry(StringUtils.parseBareAddress(uid)); if (re != null) { final User user = new User(re, mRoster.getPresence(re.getUser())); user.setAvatar(service.getAvatarService().getAvatar(user)); if (addIfNotExists) { setupUser(user); } return user; } else { Log.w(TAG, "creating Invalid user for: " + uid); final User u = new User(); u.setUserLogin(uid); u.setUserState(UserState.Invalid); return u; } }
public void updateContactList() { for (RosterEntry entry : mConnectionManager.getEntries()) { String email = entry.getUser(); if (!StringUtils.parseServer(email).equals(mConnectionManager.getDomain())) continue; if (email.equals(mConnectionManager.getUsernameEmail())) continue; Presence presence = mConnectionManager.getPresence(email); if (presence == null) return; // if disconnection happened we might get null, and in such case this method // execution can stop Contact contact; if (mContactsMap.containsKey(email)) { contact = mContactsList.get(getContactPosition(email)); contact.update(presence); } else { contact = new Contact(presence); contact.setName(entry.getName()); mContactsList.add(contact); mContactsMap.put(email, contact); } } Log.i(TAG, "updateContactList: " + mContactsList.toString()); Collections.sort(mContactsList); }
/** * retrieves the current xmpp rooster and sends a broadcast ACTION_XMPP_PRESENCE_CHANGED for every * friend does nothing if we are offline * * @return */ public ArrayList<XmppFriend> retrieveFriendList() { ArrayList<XmppFriend> friends = new ArrayList<XmppFriend>(); if (sConnection != null && sConnection.isAuthenticated()) { try { String userID = null; String status = null; Roster roster = sConnection.getRoster(); for (RosterEntry r : roster.getEntries()) { userID = r.getUser(); status = retrieveStatusMessage(userID); friends.add(new XmppFriend(userID, r.getName(), status, retrieveState(userID))); } sendFriendList(friends); } catch (Exception ex) { Log.w("Failed to retrieve Xmpp Friend list", ex); } } return friends; }
public static void main(String[] args) { Scanner inputReader = new Scanner(System.in); XMPPConnection connection = null; System.out.println("Welcome to the Multi User Chat Desktop Application."); boolean notConnected = true; while (notConnected) { System.out.println("Enter the XMPP server you would like to connect to (e.g. myserver.org):"); String xmppServer = inputReader.nextLine(); try { System.out.println("Processing... Please wait"); connection = new XMPPConnection(xmppServer); // connects to server address provided connection.connect(); System.out.println("Connection Successful!\n"); notConnected = false; } catch (Exception e) { System.out.println( "There was an issue connecting to the XMPP server '" + xmppServer + "' (We recommend jabber.org)"); } } boolean validUserAndPass = false; String userName = null; while (!validUserAndPass) { System.out.println("Please enter your username: "******"Please enter your password: "******"Validating your information..."); connection.login(userName, password); // attempts to login to the server validUserAndPass = true; System.out.println("Login Successful!\n"); } catch (Exception e) { System.out.println( "Error logging into server - Your username or password may be incorrect"); } } Connection connection2 = new XMPPConnection("jabber.org"); MultiUserChat groupChat2 = null; try { connection2.connect(); connection2.login("*****@*****.**", "opencommdesign"); } catch (XMPPException e1) { System.out.println("Hardcoded opencommdesign failed to log in"); } System.out.println("Enter a command to begin (or 'help' to see available commands)"); MultiUserChat groupChat = null; ArrayList<RosterEntry> onlineUsersInRoom = new ArrayList<RosterEntry>(); // updated when a user accepts the chat invitation boolean chatRoomGenerated = false; // checked against to make sure room is not regenerated each time a user is invited ChatManager chatmanager = null; Chat chat = null; boolean programTerminated = false; while (!programTerminated) { String input = inputReader.nextLine(); input = input .trim(); // ignores spaces before and after the command if the command itself is // correct - does not remove spaces mixed into the command if (input.startsWith(HELP_VERB) && input.length() == HELP_VERB.length()) { System.out.println(COMMAND_OPTIONS); // prints list of available commands } else if (input.equals(VIEW_ROOM_VERB)) { if (groupChat == null) { System.out.println("You are not currently in any chat rooms"); } else { System.out.println("You are currently in the '" + DEFAULT_ROOM_NAME + "' chatroom"); } } else if (input.startsWith(INVITATION_VERB)) { String userToInvite = input.substring( INVITATION_VERB.length() + 1); // +1 accounts for space after verb, isolates the username try { if (!chatRoomGenerated) { System.out.println("Initializing a default chat room..."); groupChat = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org"); groupChat.create( DEFAULT_ROOM_NAME); // initializes a default instant room, automatically placing the // user in it groupChat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); System.out.println("Default chat room initialized!"); // listen for invitation rejections groupChat.addInvitationRejectionListener( new InvitationRejectionListener() { public void invitationDeclined(String invitee, String reason) { System.out.println("User '" + invitee + "' declined your chat invitation."); System.out.println("Reason: " + reason); } }); groupChat2 = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org"); groupChat2.join(DEFAULT_ROOM_NAME); // hardcoded second user joins the room chatRoomGenerated = true; chatmanager = connection.getChatManager(); chat = chatmanager.createChat( userToInvite, new MessageListener() { public void processMessage(Chat chat, Message message) { System.out.println("Received message: " + message); } }); } groupChat.invite( userToInvite, "User '" + userName + "' has invited you to join a chat room"); } catch (XMPPException e) { System.out.println("Error occured in creating the chat room"); } } else if (input.equals(VIEW_BUDDY_VERB)) { // if user enters viewBuddyList Roster roster = connection.getRoster(); // gets other users on this connection Collection<RosterEntry> entries = roster.getEntries(); ArrayList<RosterEntry> onlineUsers = new ArrayList<RosterEntry>(); ArrayList<RosterEntry> offlineUsers = new ArrayList<RosterEntry>(); for (RosterEntry entry : entries) { if (entry .toString() .contains( "[Buddies]")) { // if other users are marked as buddies, print them to the list String user = entry.getUser(); if (roster.getPresence(user) == null) { // if user is offline, add them to offlineUsers offlineUsers.add(entry); } else { onlineUsers.add(entry); } } } System.out.println("Online Buddies in your chat room:"); if (groupChat.getOccupantsCount() == 1) { System.out.println("There are 0 buddies in your chat room"); } else { @SuppressWarnings("unchecked") Collection<String> users = (Collection<String>) groupChat.getOccupants(); for (@SuppressWarnings("unused") String user : users) { System.out.println(user); } } System.out.println("Online Buddies:"); if (onlineUsers.size() == 0) { System.out.println("There are 0 buddies online"); } else { for (RosterEntry entry : onlineUsers) { String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]")); System.out.println(user); } } System.out.println("Offline Buddies:"); if (offlineUsers.size() == 0) { System.out.println("There are 0 buddies offline"); } else { for (RosterEntry entry : offlineUsers) { String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]")); System.out.println(user); } } System.out.println(""); } else { System.out.println( "Command not recognized. Type 'help' to see a list of available commands"); } if (!programTerminated) { System.out.println("Enter a command: "); } } }
// constructors and initializers public FbContact(RosterEntry re) { String jid = re.getUser(); init(re.getName(), jid); }
/** * Returns the Jabber Userid of this contact * * @return the Jabber Userid of this contact */ public String getAddress() { if (isResolved) return rosterEntry.getUser(); else return tempId; }
/** 登陆XMPP服务器 */ public boolean login() throws RemoteException { // 未建立XMPP连接 if (!connection.isConnected()) { return false; } // 应经登陆过 if (connection.isAuthenticated()) { return true; } else { // 开始登陆 try { connection.login(account, password, imService.getString(R.string.app_name)); if (messageListener == null) { messageListener = new MessageListener(); } // 添加消息监听器 connection.addPacketListener(messageListener, new PacketTypeFilter(Message.class)); Roster roster = connection.getRoster(); if (rosterListener == null) { rosterListener = new IMClientRosterListener(); } // 添加花名册监听器 roster.addRosterListener(rosterListener); // 获取花名册 if (roster != null && roster.getEntries().size() > 0) { Uri uri = null; for (RosterEntry entry : roster.getEntries()) { // 获取联系人名片信息 VCard vCard = new VCard(); vCard.load(connection, entry.getUser()); // 用户名称 String userName = StringUtils.parseName(entry.getUser()); // 用户备注 String remarks = entry.getName(); // 通讯录的名称 String name = ""; // 名称与备注判断 if (userName.equals(remarks) && vCard != null) { // 使用联系人的昵称 name = vCard.getNickName(); } else { // 使用备注 name = remarks; } if (vCard != null) { IM.saveAvatar(vCard.getAvatar(), StringUtils.parseName(entry.getUser())); } ContentValues values = new ContentValues(); values.put(ContactsProvider.ContactColumns.ACCOUNT, entry.getUser()); values.put(ContactsProvider.ContactColumns.NAME, name); String sortStr = PinYin.getPinYin(name); values.put(ContactsProvider.ContactColumns.SORT, sortStr); values.put( ContactsProvider.ContactColumns.SECTION, sortStr.substring(0, 1).toUpperCase(Locale.ENGLISH)); // 储存联系人 if (imService .getContentResolver() .update( ContactsProvider.CONTACT_URI, values, ContactsProvider.ContactColumns.ACCOUNT + " = ?", new String[] {entry.getUser()}) == 0) { uri = imService.getContentResolver().insert(ContactsProvider.CONTACT_URI, values); } } // 发生改变,通知刷新 if (uri != null) { imService.getContentResolver().notifyChange(uri, null); } } } catch (XMPPException e) { e.printStackTrace(); } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } }
private void updateRosterEntryInDB(final RosterEntry entry) { upsertroster(getContentValuesForRosterEntry(entry), entry.getUser()); }