void CServerContext::SendPingRequest()
{
	NetServerPingRequest_t msg;
	msg.itemsTotal = 0;

	std::cout << "[SERVER] Ping?" << std::endl;

	SocketUserMap::iterator iter = clientSocketMap.begin();
	while(iter != clientSocketMap.end())
	{
		SNetSocket_t socket = iter->first;
		CUser *user = iter->second;

		if(user->GetPongTime() < lastping)
		{
			std::cout << "[SERVER] Dropping " << *user << " last reponse " << user->GetPongTime() << " / " << lastping << std::endl;

			// they haven't responded between the last ping and now
			iter = clientSocketMap.erase( iter );

			networking->DestroySocket(socket, false);
			RemoveUser(user);
			continue;
		}

		networking->SendDataOnSocket( socket, (void *)&msg, sizeof( NetServerPingRequest_t ), false );
		++iter;
	}

	lastping = time(0);
}
// 090511 LUJ, 사용자를 추가함
void CUserIPCheckMgr::AddUser( DWORD connectionIndex, const OPERATOR& operatorData, const IPINFO& ipInfo )
{
	RemoveUser( connectionIndex );

	const DWORD arraySize = sizeof( mUserArray ) / sizeof( *mUserArray );

	for( DWORD i = 0; i < arraySize; ++i )
	{
		User& user = mUserArray[ i ];

		if( user.dwIdx )
		{
			continue;
		}

		user.dwIdx = operatorData.dwOperIdx;
		user.mPower = operatorData.mPower;
		StringCopySafe(
			user.sID,
			operatorData.strOperID,
			sizeof( user.sID ) / sizeof( *( user.sID ) ) );
		StringCopySafe(
			user.mIpAddress,
			ipInfo.strIP,
			sizeof( user.mIpAddress ) / sizeof( *( user.mIpAddress ) ) );

		++mUserSize;
		break;
	}
}
Beispiel #3
0
int RoomMng::AddUser(int id, int roomid, css_stream_t* stream)
{
	UserClient* user = FindUser(id);
	if (user){ // same user login and pre-user still in room
		RemoveUser(id);
	}
	user = new UserClient(id, roomid, stream);
	if (!user){
		return -1;
	}
	UserRoom* ur = FindRoom(roomid);
	if (ur){
		ur->AddClient(user);
		stream->data = ur;
	}
	else {
		ur = new UserRoom(roomid);
		if (!ur){
			delete user;
			return -1;
		}
		else{
			room_map_.insert({ roomid, ur });
			ur->AddClient(user);
			stream->data = ur;
		}
	}
	ur->SendBackOtherOnlineUser(user);
	return 0;
}
void CServerContext::End()
{
	SocketUserMap::iterator iter = clientSocketMap.begin();
	while( iter != clientSocketMap.end() )
	{
		SNetSocket_t socket = iter->first;
		CUser *user = iter->second;

		iter = clientSocketMap.erase( iter );

		networking->DestroySocket(socket, true);
		RemoveUser(user);
	}

	if(serverSocket)
		networking->DestroyListenSocket(serverSocket, true);

	if(masterserver)
		masterserver->SetActive(false);
	if(gameserver)
		gameserver->LogOff();

	if(user)
		client->ReleaseUser(pipe, user);
	if(pipe)
		client->ReleaseSteamPipe(pipe);
}
Beispiel #5
0
void CKnights::Disband(CUser *pLeader /*= NULL*/)
{
	CString clanNotice = m_pMain->GetServerResource(m_byFlag == CLAN_TYPE ? IDS_CLAN_DESTROY : IDS_KNIGHTS_DESTROY);
	SendChat(clanNotice, m_strName);

	// TO-DO: Make this localised.
	for (int i = 0; i < MAX_USER; i++)
	{
		CUser *pUser = m_pMain->GetUnsafeUserPtr(i);
		if (pUser == NULL 
			|| pUser->m_pUserData->m_bKnights != m_sIndex 
			|| pUser == pLeader)
			continue;

		RemoveUser(pUser);
	}
	
	m_pMain->m_KnightsArray.DeleteData(m_sIndex);

	if (pLeader == NULL)
		return;

	Packet result(WIZ_KNIGHTS_PROCESS, uint8(KNIGHTS_DESTROY));
	result << uint8(1);
	pLeader->Send(&result);
}
/*
 *******************************************************************
 * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext )
 *
 * Description : The execution function is the function that will be called 
 *               during the process loop of the behavior engine, if the behavior 
 *               is defined as using an execution function. This function is not 
 *               called if the behavior is defined as a graph. This function is the 
 *               heart of the behavior: it should compute the essence of the behavior, 
 *               in an incremental way. The minimum amount of computing should be 
 *               done at each call, to leave time for the other behaviors to run. 
 *               The function receives the delay in milliseconds that has elapsed 
 *               since the last behavioral process, and should rely on this value to 
 *               manage the amount of effect it has on its computation, if the effect 
 *               of this computation relies on time.
 *
 * Parameters :
 *    behaviourContext    r   Behavior context reference, which gives access to 
 *                            frequently used global objects ( context, level, manager, etc... )
 *
 * Returns : int, If it is done, it should return CKBR_OK. If it returns 
 *                CKBR_ACTIVATENEXTFRAME, the behavior will again be called 
 *                during the next process loop.
 *
 *******************************************************************
 */
int CGBLLAERemoveUser::BehaviourFunction( const CKBehaviorContext& behaviorContext )
{
    CKBehavior *behavior=behaviorContext.Behavior;
    CKContext *context = behaviorContext.Context;
    int returnValue = 0;

    if(behavior->IsInputActive(EGBLRemoveUserBehInputs::InRemoveUser)) 
	{
        CGBLCOError error = RemoveUser(behaviorContext);

        CKParameterOut *parameterOutError = behavior->GetOutputParameter(EGBLRemoveUserParamOutputs::GetError);

        if(CGBLCOError::GBLCO_OK != error)
        {
            TGBLError::SetTGBLError(parameterOutError,CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL,GBLLAE_ERROR_REMOVEUSER,GBLLAE_ERROR_REMOVEUSER_DESC);
            behavior->ActivateOutput(EGBLRemoveUserBehOutputs::OutError);
        }
        else
        {
            behavior->ActivateOutput(EGBLRemoveUserBehOutputs::OutUserRemoved);
        }

    }
    return CKBR_OK;
}
void AXHackTrigger::OnUnUse(AXPlayerController* User)
{
	if (Role < ROLE_Authority)
	{
		//ServerOnUnUse(User);
	}

	RemoveUser(User);
}
Beispiel #8
0
void Channel::Left( User& who, const std::string& reason )
{
	RemoveUser(who.GetNick());
	//wxLogDebugFunc( wxEmptyString );
	if ( uidata.panel == 0 ) {
		wxLogError( _T("OnUserLeftChannel: ud->panel NULL") );
		return;
	}
	uidata.panel->Parted( who, TowxString(reason));
}
void UserManager::ResetMaster( CFrobDoor *frobDoor ) {
	int numUsers = GetNumUsers();
	if( numUsers > 1 ) {
		// grayman #3755 - the first pass is to establish order based on proximity to the door
		idVec3 doorCenter = frobDoor->GetClosedBox().GetCenter(); // grayman #3643 - use center of door, not origin
		//idVec3 doorOrigin = frobDoor->GetPhysics()->GetOrigin();
		idActor *closestUser = NULL;	// the user closest to the door
		int masterIndex = 0;			// index of closest user
		float minDistance = 100000;		// minimum distance of all users
		for( int i = 0 ; i < numUsers ; i++ ) {
			idActor *user = frobDoor->GetUserManager().GetUserAtIndex( i );
			if( user != NULL ) {
				float distance = ( user->GetPhysics()->GetOrigin() - doorCenter ).LengthFast();
				if( distance < minDistance ) {
					masterIndex = i;
					closestUser = user;
					minDistance = distance;
				}
			}
		}
		if( masterIndex > 0 ) { // only rearrange the queue if someone other than the current master is closer
			RemoveUser( closestUser );			// remove AI from current spot
			InsertUserAtIndex( closestUser, 0 );	// and put him at the top
		}
		// grayman #3755 - the second pass is to establish order based on who's running.
		idActor *runner = NULL;	// the user running to the door
		masterIndex = 0;		// index of running user
		for( int i = 0 ; i < numUsers ; i++ ) {
			idActor *user = frobDoor->GetUserManager().GetUserAtIndex( i );
			if( user != NULL ) {
				if( static_cast<idAI *>( user )->AI_RUN ) {
					masterIndex = i;
					runner = user;
					break;
				}
			}
		}
		if( masterIndex > 0 ) { // only rearrange the queue if someone other than the current master is running
			RemoveUser( runner );			 // remove AI from current spot
			InsertUserAtIndex( runner, 0 ); // and put him at the top
		}
	}
}
__interrupt void TIMER0_A1_VECTOR_ISR(void)
{
	unsigned char ExitLpm = 0;
  
  /* callback when timer expires */
  switch(__even_in_range(TA0IV,0xE))
  {
  case 0: break;                  
  case 2: ExitLpm = pCrystalCallback1(); RemoveUser(1); break;
  case 4: ExitLpm = pCrystalCallback2(); RemoveUser(2); break;
  case 6: ExitLpm = pCrystalCallback3(); RemoveUser(3); break;                         
  case 8: ExitLpm = pCrystalCallback4(); RemoveUser(4); break;                         
  default: break;
  }
  
  if ( ExitLpm )
  {
    EXIT_LPM_ISR();  
  }
}
Beispiel #11
0
bool CKnights::RemoveUser(CUser *pUser)
{
	if (pUser == NULL)
		return false;

	bool result = RemoveUser(pUser->m_pUserData->m_id);
	pUser->m_pUserData->m_bKnights = 0;
	pUser->m_pUserData->m_bFame = 0;
	pUser->SendClanUserStatusUpdate();
	return result;
}
Beispiel #12
0
void DeleteUser( IRState* pThis, int pUserIndex, int pUserId  )
{
   if( !ValidUserId( pThis, pUserIndex, pUserId ) )
   {
      printf( "ERROR 801\n" );
   }
   else
   {
      printf( "SUCCESS\n" );
      RemoveUser( pThis, pUserIndex, FALSE );
   }
}
__interrupt void TIMER0_A1_VECTOR_ISR(void)
{
  unsigned char ExitLpm = 0;
  
  /* callback when timer expires */
  switch(__even_in_range(TA0IV,8))
  {
  /* remove the user first in case the callback is re-enabling this user */
  case 0: break;                  
  case 2: RemoveUser(1); ExitLpm = pCrystalCallback1(); break;
  case 4: RemoveUser(2); ExitLpm = pCrystalCallback2(); break;
  case 6: RemoveUser(3); ExitLpm = pCrystalCallback3(); break;
  case 8: RemoveUser(4); ExitLpm = pCrystalCallback4(); break;
  default: break;
  }
  
  if ( ExitLpm )
  {
    EXIT_LPM_ISR();  
  }
  
}
Beispiel #14
0
XnStatus UserSelector::AddNewUser(XnUserID nUserId)
{
    UserSelectionState* pState;
    if(m_hUsersState.Get(nUserId, pState)==XN_STATUS_OK)
    {
        // the user already exists. We should remove it first as the old one is irrelevant anymore!
        RemoveUser(nUserId);
    }

    pState = CreateUserSelectionState();
    if(pState == NULL)
    {
        return XN_STATUS_ERROR;
    }
    m_hUsersState.Set(nUserId,pState); // the initial state is created in the CreateUserSelectionState
    return XN_STATUS_OK;
}
Beispiel #15
0
	ERROR_CODE Lobby::LeaveUser(const int userIndex)
	{
		RemoveUser(userIndex);

		auto pUser = FindUser(userIndex);

		if (pUser == nullptr) {
			return ERROR_CODE::LOBBY_LEAVE_USER_NVALID_UNIQUEINDEX;
		}

		pUser->LeaveLobby();

		m_UserIndexDic.erase(pUser->GetIndex());
		m_UserIDDic.erase(pUser->GetID().c_str());
		
		return ERROR_CODE::NONE;
	}
Beispiel #16
0
void CNrpLaborMarket::CreateNewFreeUsers()
{
	USERS coders, designer, composer, tester;
	core::map< NrpText, USERS* > group;
	group[ NrpCoder::ClassName() ] = &coders;
	group[ NrpDesigner::ClassName() ] = &designer;
	group[ NrpComposer::ClassName() ] = &composer;
	group[ NrpTester::ClassName() ] = &tester;

	for( u32 i=0; i < _users.size(); i++ )
	{
		CNrpUser* user = _users[ i ];
		NrpText typeName = user->ObjectTypeName();
		if( (*user)[ PARENTCOMPANY ].As<PNrpCompany>() != NULL )
			continue;

		if( core::map< NrpText, USERS* >::Node* node = group.find( typeName ) )
			node->getValue()->push_back( user );
	}

	size_t USER_GROUP_COUNT = 6;

	core::map< NrpText, USERS* >::Iterator gIter = group.getIterator();
	for( ; !gIter.atEnd(); gIter++ )
	{
		USERS& tmpList = *(gIter->getValue());
		for( u32 k=0; k < tmpList.size(); k++ )
			RemoveUser( tmpList[ k ] );

		tmpList.clear();

		for( size_t cnt=tmpList.size(); cnt < USER_GROUP_COUNT; cnt++ )
			tmpList.push_back( CreateRandomUser( gIter->getKey() ) );
	}

	gIter = group.getIterator();
	for( ; !gIter.atEnd(); gIter++ )
		for( u32 cnt=0; cnt < gIter->getValue()->size(); cnt++ )
			_users.push_back( (*gIter->getValue())[ cnt ] );

	if( _self[ USERNUMBER ] != static_cast< int >( _users.size() ) )
		PCall( APP_USER_MARKETUPDATE, NULL );

	_self[ USERNUMBER ] = static_cast< int >( _users.size() );
}
Beispiel #17
0
void VerifyExpirations( IRState* pThis )
{
   int  lCounter;

   time_t lCurrentTime = time( NULL );

   if( ( pThis->mLastCleanUp+IR_CLEANUP_DELAY)<=lCurrentTime )
   {
      for( lCounter = 0; lCounter < IR_MAX_CLIENT; lCounter++ )
      {
         if( (pThis->mUser[lCounter].mExpiration != 0)&&(pThis->mUser[lCounter].mExpiration < lCurrentTime) )
         {
            RemoveUser( pThis, lCounter, TRUE );
         }
      }
      pThis->mLastCleanUp = lCurrentTime;
   } 
}
OfflineBattle& OfflineBattle::operator=(OfflineBattle&& moved)
{
	// CAUTION: the userlist might contain pointers to the moved.m_me, which is about to go away.
	// So if it exists, remove this pointer and substitute in our own pointer to m_me.
	UserList::operator=((const UserList&&)moved);
	m_id = moved.m_id;
	m_me = moved.m_me;
	auto spec_it = m_users.find("Spectator");
	if (spec_it != m_users.end()) {
		RemoveUser("Spectator");
		OnUserAdded(m_me);
	}
	//	m_map_loaded = moved.m_map_loaded;
	//	m_game_loaded = moved.m_game_loaded;
	//	m_local_map = moved.m_local_map;
	//	m_local_mod = moved.m_local_mod;
	//	m_host_map = moved.m_host_map;
	//	m_host_mod = moved.m_host_mod;
	//	m_previous_local_mod_name = moved.m_previous_local_mod_name;
	//	m_restricted_units = moved.m_restricted_units;
	//	m_opt_wrap = moved.m_opt_wrap;
	m_opts = moved.m_opts;
	//	m_ingame = moved.m_ingame;
	//	m_auto_unspec = moved.m_auto_unspec;
	m_generating_script = moved.m_generating_script;
	//	m_rects = moved.m_rects;
	m_ready_up_map = moved.m_ready_up_map; // player name -> time counting from join/unspect
					       //	m_players_ready = moved.m_players_ready;
					       //	m_players_sync = moved.m_players_sync;
					       //	m_players_ok = moved.m_players_ok;
	m_teams_sizes = moved.m_teams_sizes;   // controlteam -> number of people in
					       //	m_ally_sizes = moved.m_ally_sizes; // allyteam -> number of people in
					       //	m_preset = moved.m_preset;
	m_is_self_in = moved.m_is_self_in;
	//	m_internal_bot_list = moved.m_internal_bot_list;
	//	m_script = moved.m_script;
	//	m_playback_file_path = moved.m_playback_file_path;
	//	m_parsed_teams = moved.m_parsed_teams;
	//	m_parsed_allies = moved.m_parsed_allies;
	//	m_internal_user_list = moved.m_internal_user_list;
	return *this;
}
Beispiel #19
0
int main(int argc, char** argv)
{
	if(argc == 1)
		Scan();
	else if(argc == 2)
	{
		if(!strcmp(argv[1], "--add") || !strcmp(argv[1], "-a"))
		{
			NewUser();
		}
		else if(!strcmp(argv[1], "--remove") || !strcmp(argv[1], "-r"))
		{
			RemoveUser();
		}
		else if(!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))
		{
			   printf ("\
Usage: %s [OPTION]\
",	      argv[0]);

 
			fputs ("\
\n\
  -a, --add                   	add user to the list\n\
  -r, --remove                  remove user from the list \n\
", stdout);

 
      fputs (("\
\n\
All user should have unique names and unique codes. Every time a tag\
is detected, a new record is added to the LOG file.\n\
\n\
"), stdout);

      printf (("\nReport bugs to <%s>.\n"), "OLIMEX");
      exit (1);

		}
		else
		{
Beispiel #20
0
LRESULT UploadQueueFrame::onSpeaker(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) {
	ctrlList.SetRedraw(FALSE);
	switch(wParam) {
	case REMOVE_ITEM: 
	{
		UploadQueueItem* i = (UploadQueueItem*)lParam;
		ctrlList.deleteItem(i);
		updateStatus();
		i->dec();
		if(BOOLSETTING(BOLD_UPLOAD_QUEUE))
			setDirty();
		break;
	}
	case REMOVE:
	{
		std::unique_ptr<UserItem> item((UserItem*)lParam);
		RemoveUser(item->getUser());
		updateStatus();
		if(BOOLSETTING(BOLD_UPLOAD_QUEUE))
			setDirty();
		break;
	}
	case ADD_ITEM:
		AddFile((UploadQueueItem*)lParam);
		updateStatus();
		ctrlList.resort();
		if(BOOLSETTING(BOLD_UPLOAD_QUEUE))
			setDirty();
		break;
	case UPDATE_ITEMS:
		for(int i = 0; i < ctrlList.GetItemCount(); i++) {
			ctrlList.updateItem(i, UploadQueueItem::COLUMN_TRANSFERRED);
			ctrlList.updateItem(i, UploadQueueItem::COLUMN_WAITING);
		}
		break;
	}
	ctrlList.SetRedraw(TRUE);
	return 0;
}
Beispiel #21
0
int AuthConfig::Run()
{
	ReadFromFile();
	ShowMainMenu();

	while (true)
	{
		std::cout << "> ";

		char key = (char)_getch();
		std::cout << key << std::endl;
		if (key == '9')
			break;

		else if (key == '1')
			ListRealms();
		else if (key == '2')
			AddRealm();
		else if (key == '3')
			RemoveRealm();
		else if (key == '4')
			ListUsers();
		else if (key == '5')
			AddUser();
		else if (key == '6')
			RemoveUser();
		else if (key == '7')
			ChangeUserRealm();
		else if (key == '8')
			ChangeUserPassword();
		else if (key == '?')
			ShowMainMenu();
		else
			UnrecognizedCmd();
	}

	return 0;
}
Beispiel #22
0
// RemoveUser
//
// The caller gets a reference, if _user is not NULL.
status_t
SecurityContext::RemoveUser(const char* name, User** _user)
{
	if (!name)
		return B_BAD_VALUE;

	ContextLocker _(this);

	// get the user
	User* user = FindUser(name);
	if (!user)
		return B_ENTRY_NOT_FOUND;
	Reference<User> userReference(user, true);

	// remove it
	status_t error = RemoveUser(user);
	if (error == B_OK && _user) {
		*_user = user;
		user->AddReference();
	}

	return error;
}
void CServerContext::HandleCallbackSocketStatus( SocketStatusCallback_t *pSocketStatus )
{
	if ( pSocketStatus->m_hListenSocket != serverSocket )
		return;

	if ( pSocketStatus->m_eSNetSocketState >= k_ESNetSocketStateDisconnecting )
	{
		SocketUserMap::iterator iter = clientSocketMap.find( pSocketStatus->m_hSocket );
		if( iter != clientSocketMap.end() )
		{
			CUser *user = iter->second;
			std::cout << "[SERVER] Client " << *user << " has disconnected." << std::endl;

			RemoveUser(user);
		}

		return;
	}

	if ( pSocketStatus->m_eSNetSocketState == k_ESNetSocketStateConnected )
		return; // we can ignore these

	std::cout << "[SERVER] Socket " << pSocketStatus->m_hListenSocket << " is now in state: " << EnumString<ESNetSocketState>::From( (ESNetSocketState)pSocketStatus->m_eSNetSocketState ) << std::endl;
}
void DisableRtosTick(void)
{
  RtosTickEnabled = 0;
  RemoveUser(TIMER0_RTOS_USER);
}
Beispiel #25
0
LRESULT WaitingUsersFrame::onSpeaker(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	// [!] IRainman opt.
	TaskQueue::List t;
	m_tasks.get(t);
	
	if (t.empty())
		return 0;
		
	CFlyBusyBool l_busy(m_spoken);
	CLockRedraw<> lockCtrlList(m_ctrlList);
	CLockRedraw<> lockCtrlQueued(ctrlQueued);
	for (auto j = t.cbegin(); j != t.cend(); ++j)
	{
		switch (j->first)
		{
			case REMOVE_WAITING_ITEM:
			{
				RemoveFile(static_cast<UploadQueueTask&>(*j->second).getItem());
			}
			break;
			case REMOVE:
			{
				RemoveUser(static_cast<UserTask&>(*j->second).getUser());
			}
			break;
			case ADD_ITEM:
			{
				AddFile(static_cast<UploadQueueTask&>(*j->second).getItem());
				m_needsResort = true;
			}
			break;
			case UPDATE_ITEMS:
			{
				const int l_item_count = m_ctrlList.GetItemCount();
				if (l_item_count)
				{
					const int l_top_index = m_ctrlList.GetTopIndex();
					const int l_count_per_page = m_ctrlList.GetCountPerPage();
					int64_t itime = GET_TIME();
					for (int i = l_top_index; i < l_count_per_page; i++)
					{
						auto ii = m_ctrlList.getItemData(i);
						if (ii)
						{
							// https://drdump.com/DumpGroup.aspx?DumpGroupID=491521
							ii->setText(UploadQueueItem::COLUMN_TRANSFERRED, Util::formatBytesW(ii->getPos()) + _T(" (") + Util::toStringW((double)ii->getPos() * 100.0 / (double)ii->getSize()) + _T("%)"));
							ii->setText(UploadQueueItem::COLUMN_WAITING, Util::formatSecondsW(itime - ii->getTime()));
							m_ctrlList.updateItem(i, UploadQueueItem::COLUMN_TRANSFERRED);
							m_ctrlList.updateItem(i, UploadQueueItem::COLUMN_WAITING);
						}
					}
				}
				if (m_needsResort)
				{
					m_ctrlList.resort();
					m_needsResort = false;
				}
				if (m_needsUpdateStatus)
				{
					if (BOOLSETTING(BOLD_WAITING_USERS))
					{
						setDirty(0);
					}
					updateStatus();
					m_needsUpdateStatus = false;
				}
			}
			break;
			default:
				dcassert(0);
		}
		if (j->first != UPDATE_ITEMS)
		{
			m_needsUpdateStatus = true;
		}
		delete j->second;
	}
	return 0;
}
void StopCrystalTimer(unsigned char TimerId)
{
  RemoveUser(TimerId);  
}
Beispiel #27
0
void Channel::Left( User& who, const wxString& reason )
{
  RemoveUser( who.GetNick() );
  ui().OnUserLeftChannel( *this, who, reason );
}
Beispiel #28
0
void ChannelAgent::MessageReceived(BMessage* msg)
{
	int32 i(0);

	switch (msg->what) {
	case M_USER_QUIT: {
		const char* nick(NULL);

		msg->FindString("nick", &nick);

		if (RemoveUser(nick)) {
			BMessage display;

			if (msg->FindMessage("display", &display) == B_NO_ERROR)
				ClientAgent::MessageReceived(&display);
		}
	} break;

	case M_USER_ADD: {
		const char* nick(NULL);
		bool ignore(false);

		int32 iStatus(STATUS_NORMAL_BIT);

		msg->FindString("nick", &nick);
		msg->FindBool("ignore", &ignore);
		if (nick == NULL) {
			printf("ERROR: attempted to AddUser an empty nick in ChannelAgent, channel: %s\n",
				   fId.String());
			break;
		}

		if (ignore) iStatus |= STATUS_IGNORE_BIT;

		AddUser(nick, iStatus);

		BMessage display;
		if (msg->FindMessage("display", &display) == B_NO_ERROR)
			ClientAgent::MessageReceived(&display);
	} break;

	case M_CHANGE_NICK: {
		const char* oldNick(NULL), *newNick(NULL);
		NameItem* item(NULL);
		int32 thePos(-1);

		if ((msg->FindString("oldnick", &oldNick) != B_OK) ||
			(msg->FindString("newnick", &newNick) != B_OK)) {
			printf("Error: invalid pointer, ChannelAgent::MessageReceived, M_CHANGE_NICK");
			break;
		}

		if (fMyNick.ICompare(oldNick) == 0 && !IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, newNick);

		if (((thePos = FindPosition(oldNick)) >= 0) &&
			((item = (static_cast<NameItem*>(fNamesList->ItemAt(thePos)))) != 0)) {
			item->SetName(newNick);
			fNamesList->SortItems(SortNames);
			if (fLastExpansion.ICompare(oldNick, fLastExpansion.Length()) == 0) {
				int32 count(fRecentNicks.CountItems());
				BString* name(NULL);

				for (i = 0; i < count; i++)
					if ((name = fRecentNicks.ItemAt(i))->ICompare(oldNick) == 0) {
						if (fLastExpansion.ICompare(newNick, fLastExpansion.Length()) == 0)
							name->SetTo(newNick);
						else
							delete fRecentNicks.RemoveItemAt(i);
						break;
					}
				count = fCompletionNicks.CountItems();
				for (i = 0; i < count; i++)
					if ((name = fCompletionNicks.ItemAt(i))->ICompare(oldNick) == 0) {
						if (fLastExpansion.ICompare(newNick, fLastExpansion.Length()) == 0)
							name->SetTo(newNick);
						else
							delete fCompletionNicks.RemoveItemAt(i);
						break;
					}
			}
		} else
			break;

		ClientAgent::MessageReceived(msg);
	} break;

	case M_CHANNEL_NAMES: {
		for (i = 0; msg->HasString("nick", i); ++i) {
			const char* nick(NULL);
			bool founder(false), protect(false), op(false), voice(false), helper(false),
				ignored(false);

			msg->FindString("nick", i, &nick);
			msg->FindBool("founder", i, &founder);
			msg->FindBool("protect", i, &protect);
			msg->FindBool("op", i, &op);
			msg->FindBool("voice", i, &voice);
			msg->FindBool("helper", i, &helper);
			msg->FindBool("ignored", i, &ignored);

			if (FindPosition(nick) < 0) {
				int32 iStatus(ignored ? STATUS_IGNORE_BIT : 0);

				if (founder) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_FOUNDER_BIT;
				} else if (protect) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_PROTECTED_BIT;
				} else if (op) {
					++nick;
					++fOpsCount;
					iStatus |= STATUS_OP_BIT;
				} else if (voice) {
					++nick;
					iStatus |= STATUS_VOICE_BIT;
				} else if (helper) {
					++nick;
					iStatus |= STATUS_HELPER_BIT;
				} else
					iStatus |= STATUS_NORMAL_BIT;

				fUserCount++;

				fNamesList->AddItem(new NameItem(nick, iStatus));
			}
		}

		fNamesList->SortItems(SortNames);

		if (!IsHidden()) {
			BString buffer;
			buffer << fOpsCount;
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String());

			buffer = "";
			buffer << fUserCount;
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_USERS, buffer.String());
		}
	} break;

	case M_RESIZE_VIEW: {
		BPoint point;
		msg->FindPoint("loc", &point);
		point.x -= Frame().left;
		float offset((int32)(point.x - (fNamesScroll->Frame().left)));
		fResize->MoveBy(offset, 0.0);
		fTextScroll->ResizeBy(offset, 0.0);
		fNamesScroll->ResizeBy(-offset, 0.0);
		fNamesScroll->MoveBy(offset, 0.0);
		BRect namesRect(0, 0, fNamesScroll->Bounds().Width(), 0);
		vision_app->SetRect("namesListRect", namesRect);
	} break;

	case M_SERVER_DISCONNECT: {
		// clear names list on disconnect
		fNamesList->ClearList();
		fOpsCount = 0;
		fUserCount = 0;

		// clear heuristics completion list - this ensures that no stale nicks are left
		// over in it after reconnect -- list will quickly be rebuilt anyhow if there
		// is any conversation whatsoever going on
		while (fRecentNicks.CountItems() > 0) delete fRecentNicks.RemoveItemAt(0L);

	} break;

	case M_REJOIN: {
		const char* newNick(NULL);

		if (msg->FindString("nickname", &newNick) != B_OK) {
			printf("Error: ChannelAgent::MessageReceived, M_REJOIN: invalid pointer\n");
			break;
		}

		fMyNick = newNick; // update nickname (might have changed on reconnect)

		if (!IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, fMyNick.String());

		Display(S_CHANNEL_RECON_REJOIN B_UTF8_ELLIPSIS "\n", C_ERROR, C_BACKGROUND, F_SERVER);

		// send join cmd
		BMessage send(M_SERVER_SEND);
		AddSend(&send, "JOIN ");
		AddSend(&send, fId);
		if (fChanKey != "") {
			AddSend(&send, " ");
			AddSend(&send, fChanKey);
		}
		AddSend(&send, endl);
	} break;

	case M_CHANNEL_TOPIC: {
		const char* theTopic(NULL);
		BString buffer;

		if (msg->FindString("topic", &theTopic) != B_OK) {
			printf("ChannelAgent::MessageReceived, M_CHANNEL_TOPIC: invalid pointer\n");
			break;
		}
		fTopic = theTopic;

		if (!IsHidden())
			vision_app->pClientWin()->pStatusView()->SetItemValue(
				STATUS_META, FilterCrap(theTopic, true).String());

		BMessage display;

		if (msg->FindMessage("display", &display) == B_NO_ERROR)
			ClientAgent::MessageReceived(&display);
	} break;

	case M_OPEN_MSGAGENT: {
		const char* theNick(NULL);
		msg->FindString("nick", &theNick);

		if (theNick == NULL) {
			NameItem* myUser;
			int32 pos = fNamesList->CurrentSelection();
			if (pos >= 0) {
				myUser = static_cast<NameItem*>(fNamesList->ItemAt(pos));
				BString targetNick = myUser->Name();
				msg->AddString("nick", targetNick.String());
			}
		}

		fSMsgr.SendMessage(msg);
	} break;

	case M_CHANNEL_GOT_KICKED: {
		const char* theChannel(NULL), *kicker(NULL), *rest(NULL);

		if ((msg->FindString("channel", &theChannel) != B_OK) ||
			(msg->FindString("kicker", &kicker) != B_OK) ||
			(msg->FindString("rest", &rest) != B_OK)) {
			printf("Error: ClientAgent::MessageReceived, M_CHANNEL_GOT_KICKED, invalid pointer\n");
			break;
		}

		BMessage wegotkicked(M_DISPLAY); // "you were kicked"
		BString buffer;
		buffer += S_CHANNEL_GOT_KICKED;
		buffer += theChannel;
		buffer += " " S_CHANNEL_GOT_KICKED2 " ";
		buffer += kicker;
		buffer += " (";
		buffer += rest;
		buffer += ")\n";
		PackDisplay(&wegotkicked, buffer.String(), C_QUIT, C_BACKGROUND, F_TEXT);

		// clean up
		fNamesList->ClearList();
		fOpsCount = 0;
		fUserCount = 0;

		fMsgr.SendMessage(&wegotkicked);

		BMessage attemptrejoin(M_DISPLAY); // "you were kicked"
		buffer = S_CHANNEL_REJOIN;
		buffer += theChannel;
		buffer += B_UTF8_ELLIPSIS "\n";
		PackDisplay(&attemptrejoin, buffer.String(), C_QUIT, C_BACKGROUND, F_TEXT);
		fMsgr.SendMessage(&attemptrejoin);

		BMessage send(M_SERVER_SEND);
		AddSend(&send, "JOIN ");
		AddSend(&send, theChannel);
		if (fChanKey != "") {
			AddSend(&send, " ");
			AddSend(&send, fChanKey);
		}
		AddSend(&send, endl);
	} break;

	case M_CHANNEL_MODE: {
		ModeEvent(msg);
	} break;

	case M_CHANNEL_MSG: {
		bool hasNick(false);
		BString tempString, theNick, knownAs;
		msg->FindString("msgz", &tempString);
		msg->FindString("nick", &theNick);
		if (theNick != fMyNick) FirstKnownAs(tempString, knownAs, &hasNick);

		if (IsHidden()) {
			UpdateStatus((hasNick) ? WIN_NICK_BIT : WIN_NEWS_BIT);

			if (hasNick) {
				if (tempString[0] == '\1') {
					tempString.RemoveFirst("\1ACTION ");
					tempString.RemoveLast("\1");
				}

				BNotification notification(B_INFORMATION_NOTIFICATION);
				notification.SetGroup(BString("Vision"));
				entry_ref ref = vision_app->AppRef();
				notification.SetOnClickFile(&ref);
				notification.SetTitle(fServerName.String());
				BString content;
				content.SetToFormat("%s - %s said: %s", fId.String(), theNick.String(),
									tempString.String());
				notification.SetContent(content);
				notification.Send();
			}
		} else if (hasNick)
			system_beep(kSoundEventNames[(uint32)seNickMentioned]);

		ClientAgent::MessageReceived(msg);
	} break;

	case M_CHANNEL_MODES: {
		const char* mode(NULL), *chan(NULL), *msgz(NULL);

		if ((msg->FindString("mode", &mode) != B_OK) || (msg->FindString("chan", &chan) != B_OK) ||
			(msg->FindString("msgz", &msgz) != B_OK)) {
			printf("Error: ChannelAgent::MessageReceived, M_CHANNEL_MODES: invalid pointer\n");
			break;
		}

		if (fId.ICompare(chan) == 0) {
			BString realMode(GetWord(mode, 1));
			int32 place(2);

			if (realMode.FindFirst("l") >= 0) fChanLimit = GetWord(mode, place++);

			if (realMode.FindFirst("k") >= 0) {
				fChanKey = GetWord(mode, place++);

				// u2 may not send the channel key, thats why we stored the /join cmd
				// in a string in ParseCmd
				if (fChanKey == "*" && fIrcdtype == IRCD_UNDERNET) {
					BString tempId(fId);
					tempId.Remove(0, 1); // remove any #, &, !, blah.

					if (vision_app->pClientWin()->joinStrings.FindFirst(tempId) < 1) {
						// can't find the join cmd for this channel in joinStrings!
					} else {
						BString joinStringsL(vision_app->pClientWin()->joinStrings);

						// FindLast to make sure we get the last attempt (user might have
						// tried several keys)
						int32 idPos(joinStringsL.FindLast(tempId));
						BString tempKeyString;
						joinStringsL.MoveInto(tempKeyString, idPos, joinStringsL.Length());

						fChanKey = GetWord(tempKeyString.String(), 2);
					}
				} // end u2-kludge stuff
			}
			fChanMode = mode;
			if (!IsHidden())
				vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_MODES,
																	  fChanMode.String());
		}

		BMessage dispMsg(M_DISPLAY);
		PackDisplay(&dispMsg, msgz, C_OP, C_BACKGROUND, F_TEXT);
		BMessenger display(this);
		display.SendMessage(&dispMsg);
	} break;

	case M_NAMES_POPUP_MODE: {
		const char* inaction(NULL);

		msg->FindString("action", &inaction);

		int32 count(0), index(0);

		BString victims, targetNick, action(inaction), modechar, polarity;

		NameItem* myUser(NULL);

		/// action ///
		if (action.FindFirst("voice") >= 0)
			modechar = "v";
		else if (action.FindFirst("op") >= 0)
			modechar = "o";
		else
			break;

		/// polarity ///
		if (action.FindFirst("de") >= 0)
			polarity += " -";
		else
			polarity += " +";

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += " ";
			victims += targetNick;
			count++;
		}

		BString command("/mode ");
		command += fId;
		command += polarity;

		for (i = 0; i < count; i++) command += modechar;

		command += victims;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_CTCP: {
		const char* inaction(NULL);

		msg->FindString("action", &inaction);

		int32 index(0);
		BString victims, targetNick, action(inaction);
		NameItem* myUser(NULL);
		action.ToUpper();

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += ",";
		}

		victims.RemoveLast(",");

		BString command("/ctcp ");
		command += victims;
		command += " ";
		command += action;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_WHOIS: {
		int32 index(0);
		BString victims, targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += ",";
		}

		victims.RemoveLast(",");

		BString command("/whois ");
		command += victims;

		ParseCmd(command.String());
	} break;

	case M_NAMES_POPUP_NOTIFY: {
		int32 index(0);
		BString victims, targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			victims += targetNick;
			victims += " ";
		}

		victims.RemoveLast(",");

		BString command("/notify ");
		command += victims;

		ParseCmd(command.String());

	} break;

	case M_NAMES_POPUP_DCCCHAT: {
		int32 index(0);
		BString targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/dcc chat ");
			command += targetNick;

			ParseCmd(command.String());
		}
	} break;

	case M_NAMES_POPUP_DCCSEND: {
		int32 index(0);
		BString targetNick;
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/dcc send ");
			command += targetNick;

			ParseCmd(command.String());
		}
	} break;

	case M_NAMES_POPUP_KICK: {
		int32 index(0);
		BString targetNick, kickMsg(vision_app->GetCommand(CMD_KICK));
		NameItem* myUser(NULL);

		/// iterate ///
		while ((i = fNamesList->CurrentSelection(index++)) >= 0) {
			myUser = static_cast<NameItem*>(fNamesList->ItemAt(i));
			targetNick = myUser->Name();

			BString command("/kick ");
			command += targetNick;
			command += " ";
			command += kickMsg;

			ParseCmd(command.String());
		}
	} break;

	case M_STATUS_ADDITEMS: {
		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(0, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(
			new StatusItem(S_STATUS_LAG, "", STATUS_ALIGN_LEFT), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(0, "", STATUS_ALIGN_LEFT),
														 true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_USERS, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_OPS, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem(S_STATUS_MODES, ""), true);

		vision_app->pClientWin()->pStatusView()->AddItem(new StatusItem("", "", STATUS_ALIGN_LEFT),
														 true);

		// The false bool for SetItemValue() tells the StatusView not to Invalidate() the view.
		// We send true on the last SetItemValue().
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_SERVER, fServerName.String(),
															  false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_LAG, fMyLag.String(), false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_NICK, fMyNick.String(), false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_MODES, fChanMode.String(),
															  false);
		vision_app->pClientWin()->pStatusView()->SetItemValue(
			STATUS_META, FilterCrap(fTopic.String(), true).String());

		BString buffer;
		buffer << fUserCount;
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_USERS, buffer.String(), false);
		buffer = "";
		buffer << fOpsCount;
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String(), true);
	} break;

	case M_CHANNEL_OPTIONS_SHOW: {
		if (fChanOpt)
			fChanOpt->Activate();
		else {
			fChanOpt = new ChannelOptions(fId.String(), this);
			fChanOpt->Show();
		}
	} break;

	case M_CHANNEL_OPTIONS_CLOSE: {
		fChanOpt = NULL;
	} break;

	case M_CLIENT_QUIT: {
		if ((msg->HasBool("vision:part") && msg->FindBool("vision:part")) ||
			(msg->HasBool("vision:winlist") && msg->FindBool("vision:winlist"))) {
			BMessage send(M_SERVER_SEND);
			AddSend(&send, "PART ");
			AddSend(&send, fId);
			if (msg->HasString("vision:partmsg")) {
				AddSend(&send, " :");
				AddSend(&send, msg->FindString("vision:partmsg"));
			}
			AddSend(&send, endl);
		}
		ClientAgent::MessageReceived(msg);
	} break;

	default:
		ClientAgent::MessageReceived(msg);
	}
}
Beispiel #29
0
void AddChatMessage( IRState* pThis, int pUserIndex, int pUserId, const char* pMessage )
{
   int  lSUIndex;
   BOOL lOK;
   int  lCounter;
   int  lLen;

   if( !ValidUserId( pThis, pUserIndex, pUserId ) )
   {
      printf( "ERROR 301" );
   }
   else
   {
      printf( "SUCCESS\n" );

      if( pMessage[0] == '/' )
      {
         /* verify if the user have super user rights */
         if(  ( pThis->mUser[ pUserIndex ].mExpiration != 0)
            &&( pThis->mUser[ pUserIndex ].mKeyID.mMajor != -1) )
         {
            lSUIndex = 0;
            lOK = FALSE;

            while( !lOK && (gSUList[ lSUIndex ].mMajor != -1) )
            {
               if(   ( gSUList[ lSUIndex ].mMajor == pThis->mUser[ pUserIndex ].mKeyID.mMajor )
                   &&( gSUList[ lSUIndex ].mMinor == pThis->mUser[ pUserIndex ].mKeyID.mMinor ) )
               {
                  lOK = TRUE;
               }
               lSUIndex++;
            }

            if( !strncmp( pMessage, "/kick ", 5 ))
            {
               if( lOK )
               {

                  /* find the user to kick (start from the end this way there is more chance to catch the good one */
                  for( lCounter = IR_MAX_CLIENT-1; lCounter >= 0; lCounter-- )
                  {
                     if( ( pThis->mUser[lCounter].mTimeStamp != 0)&&(pThis->mUser[ lCounter ].mExpiration != 0) )
                     {
                        if( !strcmp( pThis->mUser[ lCounter ].mName, pMessage+6 ))
                        {
                           /* Kick and quit */
                           if( InitLogFile() )
                           {
                              fprintf( gLogFile, "KICK %s(%d-%d) by  %s(%d-%d)\n",
                                       pThis->mUser[ lCounter ].mName,
                                       pThis->mUser[ lCounter ].mKeyID.mMajor,
                                       pThis->mUser[ lCounter ].mKeyID.mMinor,
                                       pThis->mUser[ pUserIndex ].mName,
                                       pThis->mUser[ pUserIndex ].mKeyID.mMajor,
                                       pThis->mUser[ pUserIndex ].mKeyID.mMinor );
                           }
                           RemoveUser( pThis, lCounter, TRUE );
                           break;
                        }
                     }
                  }
               }
               else
               {
               }
            }
         }
      }
      else
      {

         lLen = 0;


         pThis->mChatFifo[ pThis->mChatTail ].mTimeStamp = pThis->mTimeStamp;
   
         if( pThis->mUser[ pUserIndex ].mExpiration != 0 )
         {
            lLen += StrMaxCopy( pThis->mChatFifo[ pThis->mChatTail ].mData, pThis->mUser[ pUserIndex ].mName , IR_CHAT_MESSAGE_LEN/4 );
            pThis->mChatFifo[ pThis->mChatTail ].mData[ lLen++ ] = '>';
            pThis->mChatFifo[ pThis->mChatTail ].mData[ lLen++ ] = ' ';
         }

         StrMaxCopy( pThis->mChatFifo[ pThis->mChatTail ].mData+lLen, pMessage, IR_CHAT_MESSAGE_LEN-lLen );

         pThis->mChatTail = (pThis->mChatTail+1)%IR_MAX_CHAT_MESSAGE;

         pThis->mTimeStamp++;

         pThis->mUser[ pUserIndex ].mNbChat++;
      }
   }
}