org.jivesoftware.smackx.muc.MultiUserChatManager Java Examples

The following examples show how to use org.jivesoftware.smackx.muc.MultiUserChatManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void join(Message message) {
	// TODO 收到加入群的离线消息,被邀请进入群
	MucInvitation mi = message.getExtension("x", "xytalk:muc:invitation");
	String jid = mi.getRoomid();
	String roomname = mi.getRoomName();
	MultiUserChat muc;
	try {
		muc = MultiUserChatManager.getInstanceFor(Launcher.connection)
				.getMultiUserChat(JidCreate.entityBareFrom(jid));
		muc.join(Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));
		// 更新左侧panel,将群组UI新建出来
		createNewRoomByInvitation(jid, roomname);
	} catch (NotAMucServiceException | NoResponseException | XMPPErrorException | NotConnectedException
			| XmppStringprepException | InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example #2
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the default conference service. (ex. conference.jivesoftware.com)
 *
 * @return the default conference service to interact with MUC.
 */
public String getDefaultConferenceService() {
    if (conferenceService == null) {
        try {
            final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() );
            List<DomainBareJid> col = multiUserChatManager.getMucServiceDomains();
            if (col.size() > 0) {
                conferenceService = col.iterator().next().toString();
            }
        }
        catch (XMPPException | SmackException | InterruptedException e) {
            Log.error(e);
        }
    }

    return conferenceService;
}
 
Example #3
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new public Conference Room.
 *
 * @param roomName    the name of the room.
 * @param serviceName the service name to use (ex.conference.jivesoftware.com)
 * @return the new ChatRoom created. If an error occured, null will be returned.
 */
public ChatRoom createConferenceRoom(Localpart roomName, DomainBareJid serviceName) {
    EntityBareJid roomAddress = JidCreate.entityBareFrom(roomName, serviceName);
    final MultiUserChat chatRoom = MultiUserChatManager.getInstanceFor( SparkManager.getConnection()).getMultiUserChat( roomAddress);

    final GroupChatRoom room = UIComponentRegistry.createGroupChatRoom(chatRoom);

    try {
        LocalPreferences pref = SettingsManager.getLocalPreferences();
        Resourcepart nickname = pref.getNickname();
        chatRoom.create(nickname);

        // Send an empty room configuration form which indicates that we want
        // an instant room
        chatRoom.sendConfigurationForm(new Form( DataForm.Type.submit ));
    }
    catch (XMPPException | SmackException | InterruptedException e1) {
        Log.error("Unable to send conference room chat configuration form.", e1);
        return null;
    }

    getChatContainer().addChatRoom(room);
    return room;
}
 
Example #4
Source File: ConversationInvitation.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent actionEvent) {
       final Object obj = actionEvent.getSource();
       if (obj == joinButton) {
           Localpart name = roomName.getLocalpart();
           ConferenceUtils.enterRoomOnSameThread(name.toString(), roomName, password);
       }
       else {
           try
           {
               MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).decline( roomName, inviter, "No thank you");
           }
           catch ( SmackException.NotConnectedException | InterruptedException e )
           {
               Log.warning( "unable to decline invatation from " + inviter + " to join room " + roomName, e );
           }
       }

       // Close Container
       ChatManager chatManager = SparkManager.getChatManager();
       chatManager.getChatContainer().closeTab(this);
   }
 
Example #5
Source File: InviteSwingWorker.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public Object construct()
{
    final Set<EntityBareJid> invitedJIDs = new HashSet<>();

    final MultiUserChat groupChat = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getMultiUserChat( roomJID );

    // Send invitations
    for ( final EntityBareJid jid : invitees)
    {
        try
        {
            groupChat.invite(jid, invitation);
            invitedJIDs.add( jid );
        }
        catch ( SmackException.NotConnectedException | InterruptedException e )
        {
            Log.warning( "Unable to invite " + jid + " to " + roomJID, e );
        }
    }

    return invitedJIDs;
}
 
Example #6
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void rejectInvitationAsync(Invitation invitation) {

    Address addressGroup = invitation.getGroupAddress();

    String reason = ""; // no reason for now

    MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);
    try {

            mucMgr.decline(JidCreate.entityBareFrom(addressGroup.getAddress()), JidCreate.entityBareFrom(invitation.getSender().getAddress()), reason);

        }
        catch (Exception nce)
        {
            Log.e(ImApp.LOG_TAG,"not connected error trying to reject invite",nce);
        }
}
 
Example #7
Source File: RoomMembersPanel.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
private void inviteOrKick(final String[] usernames, String type) throws XmppStringprepException
{
	if (usernames.length == 0)
		return;
	
	MultiUserChat muc = 
MultiUserChatManager.getInstanceFor(Launcher.connection).getMultiUserChat(JidCreate.entityBareFrom(roomId));
	
	//邀请成员
    if (type.equals("invite")){
    	addMan(usernames, muc);
    }
    
    //删除成员,踢人
    if (type.equals("kick")){       	
    	kickMan(usernames, muc);       	
    }
    
    //刷新群成员UI
    updateUI();
}
 
Example #8
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getDefaultGroupChatService ()
{
    try {
        // Create a MultiUserChat using a Connection for a room
        //TODO fix this with new smack
        MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);

        if (!mucMgr.providesMucService(JidCreate.domainBareFrom(mUserJid)))
            return DEFAULT_CONFERENCE_SERVER;

        Collection<DomainBareJid> servers = mucMgr.getXMPPServiceDomains();

        //just grab the first one
        for (DomainBareJid server : servers)
            return server.toString();

    }
    catch (Exception xe)
    {
        Log.w(TAG, "Error discovering MUC server",xe);

        //unable to find conference server
        return DEFAULT_CONFERENCE_SERVER;
    }

    return DEFAULT_CONFERENCE_SERVER;
}
 
Example #9
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void mucInvitation() {
	MultiUserChatManager.getInstanceFor(Launcher.connection).addInvitationListener(new InvitationListener() {
		@Override
		public void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityJid inviter, String reason,
				String password, Message message, Invite invitation) {
			String barejid = message.getFrom().toString();
			DebugUtil.debug("被邀请加入群聊:" + barejid + reason);
			try {

				room.join(Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));

				if (barejid != null) {
					if (Launcher.currRoomId.equals(barejid)) {
						// 当前聊天者即为已有群
						// updateChatPanel(message);
					} else {
						if (Launcher.roomService.exist(barejid)) {
							// 联系人列表中存在群组,更新未读信息,则修改
							// updateRoom(message);
						} else {
							// 联系人中不存在群组,则新建一个群
							createNewRoom(message);
						}
						// dbMessagePersistence(message);
					}
				}

			} catch (NotAMucServiceException | NoResponseException | XMPPErrorException | NotConnectedException
					| XmppStringprepException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	});
}
 
Example #10
Source File: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void joinAllRooms() throws XmppStringprepException, XMPPErrorException, NoResponseException,
		NotConnectedException, InterruptedException, NotAMucServiceException {
	// TODO 启动MUC房间订阅,订阅全部房间
	// 在sqlite库中查询MUC群组
	List<Room> dbMucRooms = Launcher.roomService.findByType("m");
	for (Room roomDb : dbMucRooms) {
		if (roomDb.getRoomId() != null && !roomDb.getRoomId().isEmpty() && roomDb.getRoomId().contains("@")) {
			MultiUserChat room = MultiUserChatManager.getInstanceFor(Launcher.connection)
					.getMultiUserChat(JidCreate.entityBareFrom(roomDb.getRoomId()));
			// 将room加入堆缓存,以便重复利用
			// roomCacheService.put(roomDb.getRoomId(),room);
			// 以“username-真实姓名”为nickname进入群
			// room.join(Resourcepart.from(UserCache.CurrentUserName + "-" +
			// UserCache.CurrentUserRealName));
			MucEnterConfiguration.Builder builder = room.getEnterConfigurationBuilder(
					Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));
			// 只获取最后10条历史记录
			// builder.requestMaxStanzasHistory(10);
			// 只获取该房间最后一条消息的时间戳到当前时间戳的离线
			int historySince = MucChatService.getHistoryOffsize(roomDb.getLastChatAt());
			builder.requestHistorySince(historySince);
			// 只获取2018-5-1以来的历史记录
			// builder.requestHistorySince(new Date(2018,5,1));
			MucEnterConfiguration mucEnterConfiguration = builder.build();
			room.join(mucEnterConfiguration);

		}
	}
}
 
Example #11
Source File: RoomCreationDialog.java    From Spark with Apache License 2.0 5 votes vote down vote up
private MultiUserChat createGroupChat(String roomName, DomainBareJid serviceName) {
    String roomString = roomName.replaceAll(" ", "_") + "@" + serviceName;
    EntityBareJid room = JidCreate.entityBareFromOrThrowUnchecked(roomString);

    // Create a group chat with valid information
    return MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getMultiUserChat( room );
}
 
Example #12
Source File: RoomBrowser.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void displayRoomInformation(final EntityBareJid roomJID) {
     SwingWorker worker = new SwingWorker() {
         RoomInfo roomInfo = null;
         DiscoverItems items = null;

         @Override
public Object construct() {
             try {
                 roomInfo = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getRoomInfo( roomJID );


                 ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
                 items = manager.discoverItems(roomJID);
             }
             catch (XMPPException | SmackException | InterruptedException e) {
                 Log.error(e);
             }
             return "ok";
         }

         @Override
public void finished() {
             setupRoomInformationUI(roomJID, roomInfo, items);
         }
     };

     worker.start();
 }
 
Example #13
Source File: RoomMembersPanel.java    From xyTalk-pc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
   * 删除MucRoom,即解散群
   *
   * @param roomId
   * @throws XmppStringprepException 
   */
  private void deleteGroup(String roomId) throws XmppStringprepException
  {
      JOptionPane.showMessageDialog(null, "删除群聊:" + roomId, "删除群聊", JOptionPane.INFORMATION_MESSAGE);
      MultiUserChat muc = 
		MultiUserChatManager.getInstanceFor(Launcher.connection).getMultiUserChat(JidCreate.entityBareFrom(roomId));
      
      //发送删除消息
      List<Jid> memberForKick = new ArrayList<Jid>();

if (room.getMember()!=null && !room.getMember().isEmpty()){
	String[] oldMembers = room.getMember().split(",");
	for (String user : oldMembers){
		memberForKick.add(JidCreate.from(user + "@" + Launcher.DOMAIN) );
	} 
	MucChatService.sendKickMessage(memberForKick,room.getRoomId(),room.getName());
}
    	      
      try {
	muc.destroy("解散群组", JidCreate.entityBareFrom(roomId));
} catch (NoResponseException | XMPPErrorException | NotConnectedException | InterruptedException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
      
      //自我删除Room数据
      Launcher.roomService.delete(roomId);
      DebugUtil.debug("解散群组:"+roomId);
      //更新左侧房间UI
      RoomsPanel.getContext().notifyDataSetChanged(false);
  }
 
Example #14
Source File: BookmarksUI.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void addRegisteredServices() {
    SwingWorker worker = new SwingWorker() {

        @Override
        public Object construct() {
            try {
                if (SparkManager.getConnection().isConnected()) {
                    mucServices = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getMucServiceDomains();
                }
            }
            catch (XMPPException | SmackException | InterruptedException e) {
                Log.error("Unable to load MUC Service Names.", e);
            }
            return mucServices;
        }

        @Override
        public void finished() {
            if (mucServices == null) {
                return;
            }

            for (DomainBareJid service : mucServices) {
                if (!hasService(service)) {
                    addServiceToList(service);
                }
            }
        }
    };

    worker.start();
}
 
Example #15
Source File: OmemoService.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return the joined MUC with EntityBareJid jid, or null if its not a room and/or not joined.
 *
 * @param connection xmpp connection
 * @param jid jid (presumably) of the MUC
 * @return MultiUserChat or null if not a MUC.
 */
private static MultiUserChat getMuc(XMPPConnection connection, Jid jid) {
    EntityBareJid ebj = jid.asEntityBareJidIfPossible();
    if (ebj == null) {
        return null;
    }

    MultiUserChatManager mucm = MultiUserChatManager.getInstanceFor(connection);
    Set<EntityBareJid> joinedRooms = mucm.getJoinedRooms();
    if (joinedRooms.contains(ebj)) {
        return mucm.getMultiUserChat(ebj);
    }

    return null;
}
 
Example #16
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
public void reconnectAll ()
{
    MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);
    mucMgr.setAutoJoinOnReconnect(true);

    Enumeration<MultiUserChat> eMuc = mMUCs.elements();
    while (eMuc.hasMoreElements())
    {
        MultiUserChat muc = eMuc.nextElement();

        MultiUserChat reMuc = mucMgr.getMultiUserChat(muc.getRoom());

        try {
            DiscussionHistory history = new DiscussionHistory();
            history.setMaxStanzas(Integer.MAX_VALUE);
            reMuc.join(Resourcepart.from(mUser.getName()), null, history, SmackConfiguration.getDefaultPacketReplyTimeout());

            mMUCs.put(muc.getRoom().toString(),reMuc);
            ChatGroup group = mGroups.get(muc.getRoom().toString());

            addMucListeners(reMuc, group);
            loadMembers(muc, group);

            queryArchive(muc.getRoom());

        } catch (Exception e) {
            Log.w(TAG,"unable to join MUC: " + e.getMessage());
        }
    }
}
 
Example #17
Source File: ConferenceServices.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Adds an invitation listener to check for any MUC invites.
 */
private void addInvitationListener() {
    MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).addInvitationListener( this );
}
 
Example #18
Source File: Workgroup.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new workgroup instance using the specified workgroup JID
 * (eg [email protected]) and XMPP connection. The connection must have
 * undergone a successful login before being used to construct an instance of
 * this class.
 *
 * @param workgroupJID the JID of the workgroup.
 * @param connection   an XMPP connection which must have already undergone a
 *                     successful login.
 */
public Workgroup(EntityBareJid workgroupJID, XMPPConnection connection) {
    // Login must have been done before passing in connection.
    if (!connection.isAuthenticated()) {
        throw new IllegalStateException("Must login to server before creating workgroup.");
    }

    this.workgroupJID = workgroupJID;
    this.connection = connection;
    inQueue = false;
    invitationListeners = new CopyOnWriteArraySet<>();
    queueListeners = new CopyOnWriteArraySet<>();

    // Register as a queue listener for internal usage by this instance.
    addQueueListener(new QueueListener() {
        @Override
        public void joinedQueue() {
            inQueue = true;
        }

        @Override
        public void departedQueue() {
            inQueue = false;
            queuePosition = -1;
            queueRemainingTime = -1;
        }

        @Override
        public void queuePositionUpdated(int currentPosition) {
            queuePosition = currentPosition;
        }

        @Override
        public void queueWaitTimeUpdated(int secondsRemaining) {
            queueRemainingTime = secondsRemaining;
        }
    });

    /**
     * Internal handling of an invitation.Recieving an invitation removes the user from the queue.
     */
    MultiUserChatManager.getInstanceFor(connection).addInvitationListener(
            new org.jivesoftware.smackx.muc.InvitationListener() {
                @Override
                public void invitationReceived(XMPPConnection conn, org.jivesoftware.smackx.muc.MultiUserChat room, EntityJid inviter,
                                               String reason, String password, Message message, MUCUser.Invite invitation) {
                    inQueue = false;
                    queuePosition = -1;
                    queueRemainingTime = -1;
                }
            });

    // Register a packet listener for all the messages sent to this client.
    StanzaFilter typeFilter = new StanzaTypeFilter(Message.class);

    connection.addAsyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet) {
            handlePacket(packet);
        }
    }, typeFilter);
}
 
Example #19
Source File: MucManager.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
public MucManager() {
    // Get the MultiUserChatManager
    manager = MultiUserChatManager.getInstanceFor(XMPPManager.getInstance().getConnection());
    manager.addInvitationListener(this);
}
 
Example #20
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 4 votes vote down vote up
@Override
        public void joinChatGroupAsync(Address address, String reason) {

            String chatRoomJid = address.getBareAddress();
            String[] parts = chatRoomJid.split("@");
            String room = parts[0];

            try {

                if (mConnection == null || (!mConnection.isAuthenticated()))
                    return;

//                mBookmarkManager.addBookmarkedConference(address.getUser(),JidCreate.entityBareFrom(chatRoomJid),true,null,null);

                // Create a MultiUserChat using a Connection for a room
                MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);
                mucMgr.setAutoJoinOnReconnect(true);
                EntityBareJid crJid = JidCreate.entityBareFrom(chatRoomJid);
                MultiUserChat muc = mucMgr.getMultiUserChat( crJid);

                DiscussionHistory history = new DiscussionHistory();
                history.setMaxStanzas(Integer.MAX_VALUE);
                muc.join(Resourcepart.from(mUser.getName()), null, history, SmackConfiguration.getDefaultPacketReplyTimeout());
                String subject = muc.getSubject();

                if (TextUtils.isEmpty(subject))
                    subject = room;

                ChatGroup chatGroup = mGroups.get(chatRoomJid);

                if (chatGroup == null) {
                    chatGroup = new ChatGroup(address, subject, this);
                    mGroups.put(chatRoomJid, chatGroup);
                }

                mMUCs.put(chatRoomJid, muc);

                addMucListeners(muc, chatGroup);
                loadMembers(muc, chatGroup);

                queryArchive(crJid);

            } catch (Exception e) {
                debug(TAG,"error joining MUC",e);
            }

        }
 
Example #21
Source File: ConferenceRoomBrowser.java    From Spark with Apache License 2.0 3 votes vote down vote up
/**
    * Returns true if the room is password protected or Members only
    *
    * @param roomjid
    * @return
    */
   private boolean isPasswordProtected(EntityBareJid roomjid) {
boolean result = false;
try {

    RoomInfo rif = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getRoomInfo( roomjid );

    result = rif.isMembersOnly() || rif.isPasswordProtected();

} catch (XMPPException | SmackException | NumberFormatException | InterruptedException e) {

}

       return result;
   }
 
Example #22
Source File: OmemoManager.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Returns true, if the MUC with the EntityBareJid multiUserChat is non-anonymous and members only (prerequisite
 * for OMEMO encryption in MUC).
 *
 * @param multiUserChat MUC
 * @return true if chat supports OMEMO
 *
 * @throws XMPPException.XMPPErrorException     if there was an XMPP protocol level error
 * @throws SmackException.NotConnectedException if the connection is not connected
 * @throws InterruptedException                 if the thread is interrupted
 * @throws SmackException.NoResponseException   if the server does not respond
 */
public boolean multiUserChatSupportsOmemo(MultiUserChat multiUserChat)
        throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
        SmackException.NoResponseException {
    EntityBareJid jid = multiUserChat.getRoom();
    RoomInfo roomInfo = MultiUserChatManager.getInstanceFor(connection()).getRoomInfo(jid);
    return roomInfo.isNonanonymous() && roomInfo.isMembersOnly();
}
 
Example #23
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 2 votes vote down vote up
/**
 * Return a list of available Conference rooms from the server
 * based on the service name.
 *
 * @param serviceName the service name (ex. [email protected])
 * @return a collection of rooms.
 * @throws Exception if an error occured during fetch.
 */
public static Collection<HostedRoom> getRoomList(DomainBareJid serviceName) throws Exception {
    return MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getHostedRooms( serviceName );
}
 
Example #24
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 2 votes vote down vote up
/**
 * Return the number of occupants in a room.
 *
 * @param roomJID the full JID of the conference room. (ex. [email protected])
 * @return the number of occupants in the room if available.
 * @throws XMPPException thrown if an error occured during retrieval of the information.
 * @throws InterruptedException 
 */
public static int getNumberOfOccupants(EntityBareJid roomJID) throws SmackException, XMPPException, InterruptedException {
    final RoomInfo roomInfo = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getRoomInfo( roomJID );
    return roomInfo.getOccupantsCount();
}
 
Example #25
Source File: ConferenceRoomBrowser.java    From Spark with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a Collection of all rooms in the specified Conference Service.
 *
 * @param serviceName
 *            the name of the conference service.
 * @return a Collection of all rooms in the Conference service.
 * @throws Exception
 *             if a problem occurs while getting the room list
 */
private static Collection<HostedRoom> getRoomList(DomainBareJid serviceName)
 throws Exception {
    return MultiUserChatManager.getInstanceFor( SparkManager.getConnection() ).getHostedRooms( serviceName );
}