/** * 邀请人员 * * @param object * @return */ public String invite(JSONObject object, String sessionID) { // 被邀请人的名称 String invitedName = object.get("invitedName") + DOMAIN_NAME; // 邀请原因 String reason = (String) object.get("reason"); // 房间名称 String mucname = (String) object.get("mucname"); AbstractXMPPConnection connection = conn_map.get(sessionID); MultiUserChat muc2 = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(mucname); try { // 邀请 invitedName muc2.invite(invitedName, object.toString()); } catch (NotConnectedException e) { e.printStackTrace(); } return ""; }
/** * Invites the user to a room for the given contact name and number if the user (or someone else) * writes to this room, a SMS is send to the number * * @param number * @return true if successful, otherwise false * @throws XMPPException */ public MultiUserChat inviteRoom(String number, String contact, int mode) throws Exception { MultiUserChat muc; if (!mRooms.containsKey(number)) { Log.i("No existing chat room with " + contact + ". Creating a new one..."); muc = createRoom(number, contact, mode); mRooms.put(number, muc); } else { muc = mRooms.get(number); Log.i("Opening existing room for " + contact); if (muc != null) { Collection<Occupant> occupants = muc.getParticipants(); // Logging participants for (Occupant occupant : occupants) { Log.d(occupant.getJid() + " already in the room"); } // Invite notified addresses if needed for (String notifiedAddress : mSettings.getNotifiedAddresses().getAll()) { boolean found = false; for (Occupant occupant : occupants) { if (occupant.getJid().startsWith(notifiedAddress + "/")) { found = true; break; } } if (!found) { Log.d("Inviting notified address '" + notifiedAddress + "' in the room for " + contact); muc.invite(notifiedAddress, "SMS conversation with " + contact); } } } } return muc; }
public static void createMucChannel( String channelname, String channeltopic, int userid, int channelid) { try { if (!Application.mucchannels.containsKey(channelid)) { // create MUC MultiUserChat muc = new MultiUserChat(Application.conn, channelname + "@conference.webchat"); System.out.println("Channelname: " + channelname); muc.create(channelname); Application.mucchannels.put(channelid, muc); Form form = muc.getConfigurationForm(); Form submitForm = form.createAnswerForm(); for (Iterator<FormField> fields = form.getFields(); fields.hasNext(); ) { FormField field = (FormField) fields.next(); if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) { submitForm.setDefaultAnswer(field.getVariable()); } } List<String> owners = new ArrayList<String>(); owners.add("webchat@webchat"); submitForm.setAnswer("muc#roomconfig_roomowners", owners); muc.sendConfigurationForm(submitForm); muc.invite( models.User.find.byId(userid).username + "@webchat/Smack", "Einladung in Channel " + channelname); final int chanid = channelid; muc.sendMessage("Willkommen: Topic lautet " + channeltopic + "!"); muc.addMessageListener( new PacketListener() { @Override public void processPacket(Packet packet) { if (packet instanceof Message) { String[] temp; temp = ((Message) packet).getFrom().split("/"); if (!temp[1].equals(models.Channel.find.byId(chanid).name)) { System.out.println("Received user: "******"@webchat/Smack", "Einladung in Channel " + channelname); muc.sendMessage("Willkommen: Topic lautet" + channeltopic + "!"); } } catch (XMPPException exp) { exp.printStackTrace(); } }
/** * Creates a new MUC AND invites the user room name will be extended with an random number for * security purposes * * @param number * @param name - the name of the contact to chat via SMS with * @return * @throws XMPPException */ private MultiUserChat createRoom(String number, String name, int mode) throws Exception { MultiUserChat multiUserChat; Integer randomInt; // With "@conference.jabber.org" messages are sent several times... // Jwchat seems to work fine and is the default final String roomJID; final String subjectInviteStr; do { randomInt = mRndGen.nextInt(); } while (mRoomNumbers.contains(randomInt)); String normalizedName = name.replaceAll(" ", "_").replaceAll("[\\W]|�", ""); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { normalizedName = Normalizer.normalize(normalizedName, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""); } String cleanLogin = mSettings.getLogin().replaceAll("@", "_"); String roomUID = normalizedName + "_" + ROOM_START_TAG + randomInt + "_" + cleanLogin; switch (mode) { case MODE_SMS: roomJID = roomUID + "_SMS_" + "@" + getMUCServer(); subjectInviteStr = mCtx.getString(R.string.xmpp_muc_sms) + name; break; case MODE_SHELL: roomJID = roomUID + "_Shell_" + number + "@" + getMUCServer(); subjectInviteStr = mCtx.getString(R.string.xmpp_muc_shell) + name + " " + number; name = "Shell " + number; break; default: roomJID = null; subjectInviteStr = null; break; } Log.i("Creating room " + roomJID + " " + getRoomInt(roomJID)); // See issue 136 try { multiUserChat = new MultiUserChat(mConnection, roomJID); } catch (Exception e) { Log.e("MUC creation failed: ", e); throw new Exception("MUC creation failed for " + roomJID + ": " + e.getLocalizedMessage(), e); } try { multiUserChat.createOrJoin(name); } catch (Exception e) { Log.e("MUC creation failed: ", e); throw new Exception("MUC creation failed for " + name + ": " + e.getLocalizedMessage(), e); } try { // Since this is a private room, make the room not public and set user as owner of the room. Form submitForm = multiUserChat.getConfigurationForm().createAnswerForm(); submitForm.setAnswer("muc#roomconfig_publicroom", false); submitForm.setAnswer("muc#roomconfig_roomname", name); try { submitForm.setAnswer("muc#roomconfig_roomdesc", name); } catch (Exception ex) { Log.w("Unable to configure room description to " + name, ex); } try { submitForm.setAnswer("muc#roomconfig_whois", "anyone"); } catch (Exception ex) { Log.w("Unable to configure setting whois"); } try { List<String> owners = new ArrayList<String>(); if (mConnection.getUser() != null) { owners.add(mConnection.getUser()); } else { owners.add(mSettings.getLogin()); } Collections.addAll(owners, mSettings.getNotifiedAddresses().getAll()); submitForm.setAnswer("muc#roomconfig_roomowners", owners); submitForm.setAnswer("muc#roomconfig_membersonly", true); } catch (Exception ex) { // Password protected MUC fallback code begins here Log.w( "Unable to configure room owners on Server " + getMUCServer() + ". Falling back to room passwords", ex); // See http://xmpp.org/registrar/formtypes.html#http:--jabber.org-protocol-mucroomconfig try { if (submitForm.getField("muc#roomconfig_passwordprotectedroom") != null) { submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true); } submitForm.setAnswer("muc#roomconfig_roomsecret", mSettings.roomPassword); } catch (IllegalArgumentException iae) { // If a server doesn't provide even password protected MUC, the setAnswer // call will result in an IllegalArgumentException, which we wrap into an XMPPException // See also Issue 247 http://code.google.com/p/gtalksms/issues/detail?id=247 throw iae; } } Log.d(submitForm.getDataFormToSend().toXML().toString()); multiUserChat.sendConfigurationForm(submitForm); multiUserChat.changeSubject(subjectInviteStr); } catch (XMPPException e1) { Log.w("Unable to send conference room configuration form.", e1); send(mCtx.getString(R.string.chat_sms_muc_conf_error, e1.getMessage())); // then we also should not send an invite as the room will be locked throw e1; } for (String notifiedAddress : mSettings.getNotifiedAddresses().getAll()) { multiUserChat.invite(notifiedAddress, subjectInviteStr); } registerRoom(multiUserChat, number, name, randomInt, mode); return multiUserChat; }
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: "); } } }