/** * 同步群组聊天信息 * * @param arg NULL * * @return NULL */ void* CSyncCenter::doSyncGroupChat(void* arg) { m_bSyncGroupChatRuning = true; CDBManager* pDBManager = CDBManager::getInstance(); map<uint32_t, uint32_t> mapChangedGroup; do { mapChangedGroup.clear(); CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave"); if(pDBConn) { string strSql = "select id, lastChated from IMGroup where status=0 and lastChated >=" + int2string(m_pInstance->getLastUpdateGroup()); CResultSet* pResult = pDBConn->ExecuteQuery(strSql.c_str()); if(pResult) { while (pResult->Next()) { uint32_t nGroupId = pResult->GetInt("id"); uint32_t nLastChat = pResult->GetInt("lastChated"); if(nLastChat != 0) { mapChangedGroup[nGroupId] = nLastChat; } } delete pResult; } pDBManager->RelDBConn(pDBConn); } else { log("no db connection for teamtalk_slave"); } m_pInstance->updateLastUpdateGroup(time(NULL)); for (auto it=mapChangedGroup.begin(); it!=mapChangedGroup.end(); ++it) { uint32_t nGroupId =it->first; list<uint32_t> lsUsers; uint32_t nUpdate = it->second; CGroupModel::getInstance()->getGroupUser(nGroupId, lsUsers); for (auto it1=lsUsers.begin(); it1!=lsUsers.end(); ++it1) { uint32_t nUserId = *it1; uint32_t nSessionId = INVALID_VALUE; nSessionId = CSessionModel::getInstance()->getSessionId(nUserId, nGroupId, IM::BaseDefine::SESSION_TYPE_GROUP, true); if(nSessionId != INVALID_VALUE) { CSessionModel::getInstance()->updateSession(nSessionId, nUpdate); } else { CSessionModel::getInstance()->addSession(nUserId, nGroupId, IM::BaseDefine::SESSION_TYPE_GROUP); } } } // } while (!m_pInstance->m_pCondSync->waitTime(5*1000)); } while (m_pInstance->m_bSyncGroupChatWaitting && !(m_pInstance->m_pCondGroupChat->waitTime(5*1000))); // } while(m_pInstance->m_bSyncGroupChatWaitting); m_bSyncGroupChatRuning = false; return NULL; }
void CStatement::Action(const CDbapiEvent& e) { _TRACE(GetIdent() << " " << (void*)this << ": '" << e.GetName() << "' received from " << e.GetSource()->GetIdent()); CResultSet *rs; if (dynamic_cast<const CDbapiFetchCompletedEvent*>(&e) != 0 ) { if( m_irs != 0 && (rs = dynamic_cast<CResultSet*>(e.GetSource())) != 0 ) { if( rs == m_irs ) { m_rowCount = rs->GetTotalRows(); _TRACE("Rowcount from the last resultset: " << m_rowCount); } } } if (dynamic_cast<const CDbapiDeletedEvent*>(&e) != 0 ) { RemoveListener(e.GetSource()); if(dynamic_cast<CConnection*>(e.GetSource()) != 0 ) { _TRACE("Deleting " << GetIdent() << " " << (void*)this); delete this; } else if( m_irs != 0 && (rs = dynamic_cast<CResultSet*>(e.GetSource())) != 0 ) { if( rs == m_irs ) { _TRACE("Clearing cached CResultSet " << (void*)m_irs); m_irs = 0; } } } }
IResultSet* CCursor::Open() { CResultSet *ri = new CResultSet(m_conn, GetCursorCmd()->Open()); ri->AddListener(this); AddListener(ri); return ri; }
///////////////////////////////////////////////////////////////////////////// // Get the likelihood of a result set ///////////////////////////////////////////////////////////////////////////// double CBradleyTerry::LogLikelihood(const CResultSet &rs) const { double Result = 0; for (int i = rs.GetGames(); --i >= 0;) { double Delta = velo[rs.GetWhite(i)] - velo[rs.GetBlack(i)]; switch (rs.GetResult(i)) { case 0: Result += std::log(LossProbability(Delta)); break; case 1: Result += std::log(DrawProbability(Delta)); break; case 2: Result += std::log(WinProbability(Delta)); break; } } return Result; }
/** * <#Description#> * * @param nFromId <#nFromId description#> * @param nToId <#nToId description#> * @param nMsgId <#nMsgId description#> * @param strMsgData <#strMsgData description#> * @param nMsgType <#nMsgType description#> * @param nStatus 0获取未被删除的,1获取所有的,默认获取未被删除的 */ void CMessageModel::getLastMsg(uint32_t nFromId, uint32_t nToId, uint32_t& nMsgId, string& strMsgData, IM::BaseDefine::MsgType& nMsgType, uint32_t nStatus) { uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nFromId, nToId, false); if (nRelateId != INVALID_VALUE) { CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave"); if (pDBConn) { string strTableName = "IMMessage_" + int2string(nRelateId % 8); string strSql = "select msgId,type,content from " + strTableName + " force index (idx_relateId_status_created) where relateId= " + int2string(nRelateId) + " and status = 0 order by created desc, id desc limit 1"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if (pResultSet) { while (pResultSet->Next()) { nMsgId = pResultSet->GetInt("msgId"); nMsgType = IM::BaseDefine::MsgType(pResultSet->GetInt("type")); if (nMsgType == IM::BaseDefine::MSG_TYPE_SINGLE_AUDIO) { // "[语音]"加密后的字符串 strMsgData = strAudioEnc; } else { strMsgData = pResultSet->GetString("content"); } } delete pResultSet; } else { log("no result set: %s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); } else { log("no db connection_slave"); } } else { log("no relation between %lu and %lu", nFromId, nToId); } }
CPaymentsPage::CPaymentsPage(CFCMDB& oDB, int nMemberID) : CPropertyPage(IDD_PAYMENTS_PAGE) , m_oDB(oDB) , m_nMemberID(nMemberID) , m_oTmpSubs(m_oDB.m_oMembers, true) , m_lvGrid(this) { DEFINE_CTRL_TABLE CTRL(IDC_PAYMENTS, &m_lvGrid) END_CTRL_TABLE DEFINE_GRAVITY_TABLE CTRLGRAV(IDC_PAYMENTS, LEFT_EDGE, TOP_EDGE, RIGHT_EDGE, BOTTOM_EDGE) END_GRAVITY_TABLE // Find all the payments for this member. CResultSet oRS = m_oDB.m_oSubs.Select(CWhereCmp(CSubs::MEMBER_ID, CWhereCmp::EQUALS, m_nMemberID)); for (size_t i = 0; i < oRS.Count(); i++) { CRow& oCurRow = oRS[i]; CRow& oCpyRow = m_oTmpSubs.CreateRow(); CRow* pItmRow = m_oDB.m_oBalSheet.SelectRow(CBalSheet::ID, oCurRow[CSubs::ITEM_ID].ToValue()); ASSERT(pItmRow != NULL); // Copy data. oCpyRow[CTmpSubs::ITEM_ID] = oCurRow[CSubs::ITEM_ID]; oCpyRow[CTmpSubs::MEMBER_ID] = oCurRow[CSubs::MEMBER_ID]; oCpyRow[CTmpSubs::FEE] = oCurRow[CSubs::FEE]; oCpyRow[CTmpSubs::PAID] = oCurRow[CSubs::PAID]; oCpyRow[CTmpSubs::ITEM_DATE] = pItmRow->Field(CBalSheet::DATE); oCpyRow[CTmpSubs::ITEM_NAME] = pItmRow->Field(CBalSheet::NAME); // Insert into tmp table. m_oTmpSubs.InsertRow(oCpyRow, false); } // Initialise the grid. m_lvGrid.Columns(NUM_COLUMNS, Columns); }
bool CGroupModel::removeGroup(uint32_t nUserId, uint32_t nGroupId, list<uint32_t>& lsCurUserId) { bool bRet = false; CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("dffxIMDB_master"); set<uint32_t> setGroupUsers; if(pDBConn) { string strSql = "select creator from IMGroup where id="+int2string(nGroupId); CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if(pResultSet) { uint32_t nCreator; while (pResultSet->Next()) { nCreator = pResultSet->GetInt("creator"); } if(0 == nCreator || nCreator == nUserId) { //设置群组不可用。 strSql = "update IMGroup set status=0 where id="+int2string(nGroupId); bRet = pDBConn->ExecuteUpdate(strSql.c_str()); } pResultSet->Clear(); } if (bRet) { strSql = "select userId from IMGroupMember where groupId="+int2string(nGroupId); CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if(pResultSet) { while (pResultSet->Next()) { uint32_t nId = pResultSet->GetInt("userId"); setGroupUsers.insert(nId); } pResultSet->Clear(); } } pDBManager->RelDBConn(pDBConn); } if(bRet) { bRet = removeMember(nGroupId, setGroupUsers, lsCurUserId); } return bRet; }
void CMessageModel::getMessageDays(uint32_t nUserId, uint32_t nPeerId, list<string>& lsDay) { uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nUserId, nPeerId, false); if (nRelateId != INVALID_VALUE) { CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave"); if (pDBConn) { string strTableName = "IMMessage_" + int2string(nRelateId % 8); string strSql = "select date_format(from_unixtime(created), '%Y-%m-%d') as day from " + strTableName + " where relateId = " + int2string(nRelateId) + " and status = 0 group by day order by day desc"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if (pResultSet) { while (pResultSet->Next()) { lsDay.push_back(pResultSet->GetString("day")); } delete pResultSet; } else { log("no result set: %s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); } else { log("no db connection for teamtalk_slave"); } } else { log("no relation between %lu and %lu", nUserId, nPeerId); } }
void CGroupModel::getGroupInfo(map<uint32_t,IM::BaseDefine::GroupVersionInfo>& mapGroupId, list<IM::BaseDefine::GroupInfo>& lsGroupInfo) { if (!mapGroupId.empty()) { CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("dffxIMDB_slave"); if (pDBConn) { string strClause; bool bFirst = true; for(auto it=mapGroupId.begin(); it!=mapGroupId.end(); ++it) { if(bFirst) { bFirst = false; strClause = int2string(it->first); } else { strClause += ("," + int2string(it->first)); } } string strSql = "select * from IMGroup where id in (" + strClause + ") order by updated desc"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if(pResultSet) { while (pResultSet->Next()) { uint32_t nGroupId = pResultSet->GetInt("id"); uint32_t nVersion = pResultSet->GetInt("version"); if(mapGroupId[nGroupId].version() < nVersion) { IM::BaseDefine::GroupInfo cGroupInfo; cGroupInfo.set_group_id(nGroupId); cGroupInfo.set_version(nVersion); cGroupInfo.set_group_name(pResultSet->GetString("name")); cGroupInfo.set_group_avatar(pResultSet->GetString("avatar")); IM::BaseDefine::GroupType nGroupType = IM::BaseDefine::GroupType(pResultSet->GetInt("type")); if(IM::BaseDefine::GroupType_IsValid(nGroupType)) { cGroupInfo.set_group_type(nGroupType); cGroupInfo.set_group_creator_id(pResultSet->GetInt("creator")); lsGroupInfo.push_back(cGroupInfo); } else { log("invalid groupType. groupId=%u, groupType=%u", nGroupId, nGroupType); } } } pResultSet->Clear(); } else { log("no result set for sql:%s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); if(!lsGroupInfo.empty()) { fillGroupMember(lsGroupInfo); } } else { log("no db connection for dffxIMDB_slave"); } } else { log("no ids in map"); } }
resultid_t runWTTI(const char* url, std::string& dbName, unsigned int wttiRunID, unsigned int shardNumber, int webkitTimeout) { std::string strQuery; sem_init( &(CWebPage::Instance()->sm_hostSemaphore), 0, 0 ); sem_init( &(CWebPage::Instance()->sm_threadControlSemaphore), 0, 0 ); #ifdef SHARD_AWARE ConnectionPtr connection( new Connection( CConfig::getShardServer(shardNumber), CConfig::getShardDatabase(shardNumber), CConfig::getShardUser(shardNumber), CConfig::getShardPass(shardNumber), CConfig::getDBRetryTime())); #else ConnectionPtr connection( new Connection( CConfig::getDBServer(), CConfig::getDBDatabase(), CConfig::getDBUser(), CConfig::getDBPass(), CConfig::getDBRetryTime())); #endif std::string urlToTest; // Get URL from the WttiTests table. ResultPtr resultUrl; strQuery = Format(SQL_WTTI_SELECT_URL, wttiRunID); resultUrl = connection->Query(strQuery.c_str()); if ( resultUrl->Next() ) { RowPtr row = resultUrl->GetCurrentRow(); urlToTest = row->GetFieldString(1); Trace("Rows:", "", resultUrl->GetRowCount()); } resultid_t dailyResultID = 0; PackDiagStorage store; int pageID = 0; CResultSet resultSet; CTcp* pTcpConnection = new CTcp("", 0); // Turn CSS Parsing on permanently. CWebPage::Instance()->sm_doCssParsing = 1; //Turn SSL validation on permanently CWebPage::Instance()->sm_doSslValidation = 1; CTcp::setDoSslValidation(1); // create the new web page object CWebPage* pPage = new CWebPage( resultSet, pTcpConnection, 0, SC_SERVICE_BENCHMARK, urlToTest, // url pageID, // page id SC_WEBPAGE_TYPE_IMED, // page type true, // reset cookies std::string(), // auth user std::string(), // auth pass DOWNLOAD_THRESHOLD_SECS, // download threshold true, // reset cache CConfig::getServerID(), SC_WEBPAGE_STATUS_OK, // bodge to be status live page HTTP_METHOD_GET, // bodge to get GET by default std::string(), std::vector<std::string>(), std::vector<char>(), // emptyVector, // bodge - no form variables std::string() // fileStr // bodge - no file variables ); // reset the counters pPage->resetPage(); // record when we started the test //pPage->setStartTime(); // make sure we don't report a hacking / login failure // pPage->phraseWasFound(); // Set that a connection exists to this host. //pPage->isHostConnectionsExceeded(static_cast<std::string>(url)); // do the load of this page //pPage->load(); // add the page just loaded to the list of those done so it doesn't get done again // via a redirect //CWebPage::AddURLDone(url); // reset the first byte count for the page //pPage->resetSpeedCounters(); MultiThreadSetup(); // ---------------------- // --- THREAD MANAGER --- // ---------------------- std::string protoAndHost; protoAndHost = urlToTest; // Calculate protocol type. if (strncasecmp (protoAndHost.c_str(), "http://", 7) == 0) { std::string::size_type hostLength = protoAndHost.find("/", 7); if (hostLength != std::string::npos) protoAndHost = protoAndHost.substr(0, hostLength); } else if (strncasecmp (protoAndHost.c_str(), "https://", 8) == 0) { std::string::size_type hostLength = protoAndHost.find("/", 8); if (hostLength != std::string::npos) protoAndHost = protoAndHost.substr(0, hostLength); } else { std::string::size_type hostLength = protoAndHost.find("/"); if (hostLength != std::string::npos) protoAndHost = "http://" + protoAndHost.substr(0, hostLength); else protoAndHost = protoAndHost.insert(0, "http://"); } // Add the host that we're about to connect to so it does not get added again. { Mutex::Lock lock(CWebPage::Instance()->sm_connectedHostsLock); CWebPage::Instance()->sm_connectedHosts.push_back(std::make_pair(true, protoAndHost)); } std::vector<ThreadArgs*> threadArgsVector; // JYLS WEBKIT START #ifndef SC_NON_WEBKIT #ifdef SC_WEBKIT_V89 curlwrapper_init(pPage, startThread); //Use the default value from the opt file for these ww_setMaxNumberOfThreadsPerHost(CConfig::getDefaultMaxThreadsPerHost()); ww_setMaxTotalNumberOfThreads(CConfig::getDefaultMaxTotalThreads()); ww_setScreenXDimension(CConfig::getScreenXDimension()); ww_setScreenYDimension(CConfig::getScreenYDimension()); ww_setJavascriptTimeout(CConfig::getJsExecutionTimeout()); ww_loadPageByWebkit(pPage->getURL().c_str(), true, DOWNLOAD_THRESHOLD_SECS, webkitTimeout); #else bool isJavascriptEnabled = true; soupwrapper_init(pPage, startThread); ww_setPageId(pageID); ww_setWebkitTimeout(webkitTimeout); ww_setWebkitTimeoutHard(CConfig::getWebkitHardTimeout()); load_page_by_webkit(pPage->getURL(), isJavascriptEnabled); #endif // SC_WEBKIT_V89 #else std::vector<pthread_t> threadIds; pthread_t threadId; int res = 0; unsigned int maxThreadsPerHost = 0; if (maxThreadsPerHost == 0) maxThreadsPerHost = CConfig::getDefaultMaxThreadsPerHost(); //Limit the value of maxThreadsPerHost if (maxThreadsPerHost > CConfig::getMaxThreadsPerHostLimit()) maxThreadsPerHost = CConfig::getMaxThreadsPerHostLimit(); unsigned int numThreads = maxThreadsPerHost; for (unsigned int a = 0; a < numThreads; ++a) { ThreadArgs* args1 = new ThreadArgs; args1->isFirstPage = (a == 0); args1->pPage = pPage; args1->host = protoAndHost; res = pthread_create(&(threadId), NULL, startThread, (void*)args1); if ( res != 0 ) { LogError("Failed to start thread for", protoAndHost.c_str(), 0); } else { threadIds.push_back(threadId); threadArgsVector.push_back(args1); // Wait for the second thread to signal it has started. sem_wait(&(CWebPage::Instance()->sm_threadControlSemaphore)); } } std::vector<CWebPage::HostPair>::const_iterator hostIt; Trace("before starting threads", "", 0); while ((CWebPage::getUrlListSize()) > 0 || (CWebPage::Instance()->sm_numWorkingThreads > 0)) { { Mutex::Lock lock(CWebPage::Instance()->sm_connectedHostsLock); for ( hostIt = CWebPage::Instance()->sm_connectedHosts.begin(); hostIt != CWebPage::Instance()->sm_connectedHosts.end(); ++hostIt ) { if ( !(hostIt->first) ) { unsigned int numThreads = maxThreadsPerHost; for (unsigned int a = 0; a < numThreads; ++a) { bool errorOccured = false; std::string hostToConnect; hostToConnect.assign(hostIt->second); // Start threads per new host encountered. Trace("Starting threads for", hostIt->second.c_str(), 0); ThreadArgs* args2 = new ThreadArgs; args2->isFirstPage = false; args2->pPage = pPage; args2->host = hostToConnect; res = pthread_create(&(threadId), NULL, startThread, (void*)args2); if ( res != 0 ) { LogError("Failed to start thread for", hostIt->second.c_str(), 2); errorOccured = true; } else { threadIds.push_back(threadId); threadArgsVector.push_back(args2); // Wait for thread to start. sem_wait(&(CWebPage::Instance()->sm_threadControlSemaphore)); } // Connected ok. hostIt->first = true; } } } } // Wait for more hosts to be encountered. sem_wait(&(CWebPage::Instance()->sm_hostSemaphore)); } #endif // SC_NON_WEBKIT // JYLS WEBKIT END Trace("Deleting semaphore", "", 0); sem_destroy(&(CWebPage::Instance()->sm_hostSemaphore)); sem_destroy(&(CWebPage::Instance()->sm_threadControlSemaphore)); #ifdef SC_NON_WEBKIT // Write debug information if components remain. if (CWebPage::getUrlListSize() > 0) { CWebPage::writeThreadsDebug(); int count = 0; std::vector<ThreadArgs*>::const_iterator threadsIt; for (threadsIt = threadArgsVector.begin(); threadsIt != threadArgsVector.end(); ++threadsIt) { LogInfo("Threads started=", (*threadsIt)->host.c_str(), count); ++count; } } #endif // SC_NON_WEBKIT #ifndef SC_NON_WEBKIT // Sleep to allow for extra components from eg javascript usleep(1000000); //Actually check how many threads are running, go ahead if 0 while (CWebPage::Instance()->sm_numWorkingThreads) { usleep(10000); } #else void* threadResult; // Join started threads. for (unsigned int i = 0; i < threadIds.size(); ++i) { res = pthread_join(threadIds[i], &threadResult); if (res != 0) { LogError("Unable to join thread", "", res); } else { Trace("Joined thread", "", res); } } #endif // SC_NON_WEBKIT // Delete all ThreadArgs used. while ( !threadArgsVector.empty() ) { delete threadArgsVector.back(); threadArgsVector.pop_back(); } setResultCode(pPage, CWebPage::Instance()->sm_firstPageResultCode); try { Trace("Connecting to db", "", 0); std::string requestStr; std::string headerStr; std::string htmlStr; std::string extraInfoStr; // extra info for ResultHeader if (!resultSet.getResultDetails().empty()) { const CResultDetail* pResultDetail = resultSet.getFirstResultDetail(); requestStr = pResultDetail->getRequest(); headerStr = pResultDetail->getHeaders(); htmlStr = pResultDetail->getPageText(); extraInfoStr = pResultDetail->getExtraInfo(); } const bool pageInError = pPage->getOverallResultCode() != SC_HEADER_RESULT_SUCCESS && pPage->getOverallResultCode() != SC_HEADER_RESULT_DUMMY_TRANSACTION; // 3.0.0 Daily ResultHeader tables StoreHeaderDaily( connection, resultSet, pPage->getPageID(), CConfig::getServerID(), pPage->getStartTimeStr(), pPage->getOverallResultCode(), pPage->getDNSTimeOffsetMs(), pPage->getConnectTimeOffsetMs(), pPage->getTotalLastByteTimeOffsetMs(), pPage->getTotalBytes(), &dailyResultID, pPage->getFirstDataTimeOffsetMs(), pPage->getDailyTableName(), PackDiagOverride(), store, pageInError, false, SC_TEST_TYPE_WTTI, 0, 0, 0, CSCGlobal::gAgentVersion, pPage->getTotalGzipBytes(), false, //diagstored pPage->getSslConnectTimeOffsetMs(), pPage->getRequestSentTimeOffsetMs(), pPage->getRequestHeaderSize(), pPage->getRequestContentSize(), pPage->getResponseHeaderSize()); // now store all the detail - always do this for wtti int ComponentNo = 1; for (CResultSet::ResultList::const_iterator p = resultSet.getResultDetails().begin(); p != resultSet.getResultDetails().end(); ++p, ++ComponentNo) { // now go and get the rest of the files - with threads if (const CResultDetail* pResultDetail = p->pResultDetail) { pResultDetail->setComponentNo(ComponentNo); // 3.0.0 Daily ResultDetail tables StoreResultDaily( connection, resultSet, ComponentNo, pResultDetail, dailyResultID, pPage->getDailyTableName()); } } } catch (const std::exception &e) { Trace("Exception caught", e.what(), 0); LogError2("Exception Caught:", e.what(), 0, SC_ERR_GROUP_AGENT, SC_ERR_CODE_WTTI); return 0; } #ifdef SHARD_AWARE // Write the result ID back to the transient table so the website can pick it up. strQuery = Format(SQL_WTTI_INSERT_RESULTID, dailyResultID, wttiRunID); Trace("Issuing query", strQuery.c_str(), dailyResultID); connection->Query(strQuery); #endif // dbName = pPage->getDailyTableName(); // complete it delete pPage; pPage = NULL; MultiThreadCleanup(); // Remove /tmp/session_id.<pid>p.host files long int uniqueId = getpid(); std::string identifier = WTTP_SESSION_ID_IDENTIFIER; strQuery = Format("rm -f /tmp/session_id.%ld%s.*", uniqueId, identifier.c_str()); int ret = system(strQuery.c_str()); Trace("System call returned", strQuery.c_str(), ret); return dailyResultID; }
bool CInterLoginStrategy::doLogin(const std::string &strName, const std::string &strPass, IM::BaseDefine::UserInfo& user) { bool bRet = false; CDBManager* pDBManger = CDBManager::getInstance(); CDBConn* pDBConn = pDBManger->GetDBConn("teamtalk_slave"); if (pDBConn) { string strSql = "select * from IMUser where name='" + strName + "' and status=0"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if(pResultSet) { string strResult, strSalt; uint32_t nId, nGender, nDeptId, nStatus; string strNick, strAvatar, strEmail, strRealName, strTel, strDomain,strSignInfo; while (pResultSet->Next()) { nId = pResultSet->GetInt("id"); strResult = pResultSet->GetString("password"); strSalt = pResultSet->GetString("salt"); strNick = pResultSet->GetString("nick"); nGender = pResultSet->GetInt("sex"); strRealName = pResultSet->GetString("name"); strDomain = pResultSet->GetString("domain"); strTel = pResultSet->GetString("phone"); strEmail = pResultSet->GetString("email"); strAvatar = pResultSet->GetString("avatar"); nDeptId = pResultSet->GetInt("departId"); nStatus = pResultSet->GetInt("status"); strSignInfo = pResultSet->GetString("sign_info"); } string strInPass = strPass + strSalt; char szMd5[33]; CMd5::MD5_Calculate(strInPass.c_str(), strInPass.length(), szMd5); string strOutPass(szMd5); if(strOutPass == strResult) { bRet = true; user.set_user_id(nId); user.set_user_nick_name(strNick); user.set_user_gender(nGender); user.set_user_real_name(strRealName); user.set_user_domain(strDomain); user.set_user_tel(strTel); user.set_email(strEmail); user.set_avatar_url(strAvatar); user.set_department_id(nDeptId); user.set_status(nStatus); user.set_sign_info(strSignInfo); } delete pResultSet; } pDBManger->RelDBConn(pDBConn); } return bRet; }
int CBayeselo::GetPlayers() { return rs.GetPlayers(); }
void CMessageModel::getMessageDuringTime(uint32_t nUserId, uint32_t nPeerId, uint32_t nStartTime, uint32_t nEndTime, uint32_t nOffset, uint32_t nCount, list<IM::BaseDefine::MsgInfo>& lsMsg) { uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nUserId, nPeerId, false); if (nRelateId != INVALID_VALUE) { CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave"); if (pDBConn) { string strTableName = "IMMessage_" + int2string(nRelateId % 8); string strSql; if (nCount == 0) { strSql = "select * from " + strTableName + " force index (idx_relateId_status_created) where relateId= " + int2string(nRelateId) + " and status = 0 and created >= " + int2string(nStartTime) + " and created <= " + int2string(nEndTime) + " order by created desc"; } else { strSql = "select * from " + strTableName + " force index (idx_relateId_status_created) where relateId= " + int2string(nRelateId) + " and status = 0 and created >= " + int2string(nStartTime) + " and created <= " + int2string(nEndTime) + " order by created desc limit " + int2string(nOffset) + "," + int2string(nCount); } CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if (pResultSet) { while (pResultSet->Next()) { IM::BaseDefine::MsgInfo cMsg; cMsg.set_msg_id(pResultSet->GetInt("msgId")); cMsg.set_from_session_id(pResultSet->GetInt("fromId")); cMsg.set_create_time(pResultSet->GetInt("created")); IM::BaseDefine::MsgType nMsgType = IM::BaseDefine::MsgType(pResultSet->GetInt("type")); if(IM::BaseDefine::MsgType_IsValid(nMsgType)) { cMsg.set_msg_type(nMsgType); cMsg.set_msg_data(pResultSet->GetString("content")); lsMsg.push_back(cMsg); } else { log("invalid msgType. userId=%u, peerId=%u, startTime=%u, endTime=%u, offset=%u, size=%u, msgType=%u, msgId=%u", nUserId, nPeerId, nStartTime, nEndTime, nOffset, nCount, nMsgType, pResultSet->GetInt("msgId")); } } delete pResultSet; } else { log("no result set: %s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); if (!lsMsg.empty()) { CAudioModel::getInstance()->readAudios(lsMsg); } } else { log("no db connection for teamtalk_slave"); } } else { log("no relation between %lu and %lu", nUserId, nPeerId); } }
void CMessageModel::getMsgByMsgId(uint32_t nUserId, uint32_t nPeerId, const list<uint32_t> &lsMsgId, list<IM::BaseDefine::MsgInfo> &lsMsg) { if(lsMsgId.empty()) { return ; } uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nUserId, nPeerId, false); if(nRelateId == INVALID_VALUE) { log("invalid relation id between %u and %u", nUserId, nPeerId); return; } CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave"); if (pDBConn) { string strTableName = "IMMessage_" + int2string(nRelateId % 8); string strClause ; bool bFirst = true; for(auto it= lsMsgId.begin(); it!=lsMsgId.end();++it) { if (bFirst) { bFirst = false; strClause = int2string(*it); } else { strClause += ("," + int2string(*it)); } } string strSql = "select * from " + strTableName + " where relateId=" + int2string(nRelateId) + " and status=0 and msgId in (" + strClause + ") order by created desc, id desc limit 100"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); if (pResultSet) { while (pResultSet->Next()) { IM::BaseDefine::MsgInfo msg; msg.set_msg_id(pResultSet->GetInt("msgId")); msg.set_from_session_id(pResultSet->GetInt("fromId")); msg.set_create_time(pResultSet->GetInt("created")); IM::BaseDefine::MsgType nMsgType = IM::BaseDefine::MsgType(pResultSet->GetInt("type")); if(IM::BaseDefine::MsgType_IsValid(nMsgType)) { msg.set_msg_type(nMsgType); msg.set_msg_data(pResultSet->GetString("content")); lsMsg.push_back(msg); } else { log("invalid msgType. userId=%u, peerId=%u, msgType=%u, msgId=%u", nUserId, nPeerId, nMsgType, msg.msg_id()); } } delete pResultSet; } else { log("no result set for sql:%s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); if(!lsMsg.empty()) { CAudioModel::getInstance()->readAudios(lsMsg); } } else { log("no db connection for teamtalk_slave"); } }
float CBayeselo::CountGames(int i) { return rs.CountGames(i); }
bool CGroupModel::insertNewMember(uint32_t nGroupId, set<uint32_t>& setUsers) { bool bRet = false; uint32_t nUserCnt = (uint32_t)setUsers.size(); if(nGroupId != INVALID_VALUE && nUserCnt > 0) { CDBManager* pDBManager = CDBManager::getInstance(); CDBConn* pDBConn = pDBManager->GetDBConn("dffxIMDB_slave"); if (pDBConn) { uint32_t nCreated = (uint32_t)time(NULL); // 获取 已经存在群里的用户 string strClause; bool bFirst = true; for (auto it=setUsers.begin(); it!=setUsers.end(); ++it) { if(bFirst) { bFirst = false; strClause = int2string(*it); } else { strClause += ("," + int2string(*it)); } } string strSql = "select userId from IMGroupMember where groupId=" + int2string(nGroupId) + " and userId in (" + strClause + ")"; CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str()); set<uint32_t> setHasUser; if(pResultSet) { while (pResultSet->Next()) { setHasUser.insert(pResultSet->GetInt("userId")); } pResultSet->Clear(); } else { log("no result for sql:%s", strSql.c_str()); } pDBManager->RelDBConn(pDBConn); pDBConn = pDBManager->GetDBConn("dffxIMDB_master"); if (pDBConn) { CacheManager* pCacheManager = CacheManager::getInstance(); CacheConn* pCacheConn = pCacheManager->GetCacheConn("group_member"); if (pCacheConn) { // 设置已经存在群中人的状态 if (!setHasUser.empty()) { strClause.clear(); bFirst = true; for (auto it=setHasUser.begin(); it!=setHasUser.end(); ++it) { if(bFirst) { bFirst = false; strClause = int2string(*it); } else { strClause += ("," + int2string(*it)); } } strSql = "update IMGroupMember set status=0, updated="+int2string(nCreated)+" where groupId=" + int2string(nGroupId) + " and userId in (" + strClause + ")"; pDBConn->ExecuteUpdate(strSql.c_str()); } strSql = "insert into IMGroupMember(`groupId`, `userId`, `status`, `created`, `updated`) values\ (?,?,?,?,?)"; //插入新成员 auto it = setUsers.begin(); uint32_t nStatus = 0; uint32_t nIncMemberCnt = 0; for (;it != setUsers.end();) { uint32_t nUserId = *it; if(setHasUser.find(nUserId) == setHasUser.end()) { CPrepareStatement* pStmt = new CPrepareStatement(); if (pStmt->Init(pDBConn->GetMysql(), strSql)) { uint32_t index = 0; pStmt->SetParam(index++, nGroupId); pStmt->SetParam(index++, nUserId); pStmt->SetParam(index++, nStatus); pStmt->SetParam(index++, nCreated); pStmt->SetParam(index++, nCreated); pStmt->ExecuteUpdate(); ++nIncMemberCnt; delete pStmt; } else { setUsers.erase(it++); delete pStmt; continue; } } ++it; } if(nIncMemberCnt != 0) { strSql = "update IMGroup set userCnt=userCnt+" + int2string(nIncMemberCnt) + " where id="+int2string(nGroupId); pDBConn->ExecuteUpdate(strSql.c_str()); } //更新一份到redis中 string strKey = "group_member_"+int2string(nGroupId); for(auto it = setUsers.begin(); it!=setUsers.end(); ++it) { pCacheConn->hset(strKey, int2string(*it), int2string(nCreated)); } pCacheManager->RelCacheConn(pCacheConn); bRet = true; } else { log("no cache connection"); } pDBManager->RelDBConn(pDBConn); } else {
///////////////////////////////////////////////////////////////////////////// // Read all data for Elo calculation ///////////////////////////////////////////////////////////////////////////// void EloDataFromFile(CPGNLex &pgnlex, CResultSet &rs, std::vector<std::string> &vNames) { int Players = 0; int Ignored = 0; // // Add current players to the name map // std::map<std::string, int> NameMap; for (int i = vNames.size(); --i >= 0;) { std::pair<const std::string, int> Pair(vNames[i], i); NameMap.insert(Pair); Players++; } // // Loop over games // while (1) { CSTR str; int fTheEnd = CPGN::ReadSTR(str, pgnlex); SkipGame(pgnlex); if (!fTheEnd) { // // Ignore unknown results // int r = str.GetResult(); if (r < 0 || r > 2) { Ignored++; } else { std::string sWhite(str.GetWhite()); std::string sBlack(str.GetBlack()); { std::pair<const std::string, int> Pair(sWhite, Players); if (NameMap.insert(Pair).second) { Players++; vNames.push_back(sWhite); } } { std::pair<const std::string, int> Pair(sBlack, Players); if (NameMap.insert(Pair).second) { Players++; vNames.push_back(sBlack); } } int WhitePlayer = NameMap.find(sWhite)->second; int BlackPlayer = NameMap.find(sBlack)->second; rs.Append(WhitePlayer, BlackPlayer, r); } } if (rs.GetGames() % 1000 == 0 || fTheEnd) { std::cerr << rs.GetGames() << " game(s) loaded, "; std::cerr << Ignored << " game(s) with unknown result ignored.\r"; } if (fTheEnd) { std::cerr << '\n'; break; } } }
void CBayeselo::Append(unsigned w, unsigned b, unsigned r) { rs.Append(w, b, r); }