Exemplo n.º 1
0
void GaduSearchService::handleEventPubdir50SearchReply(struct gg_event *e)
{
	gg_pubdir50_t res = e->event.pubdir50;

	ContactList results;

	int count = gg_pubdir50_count(res);
	kdebugmf(KDEBUG_NETWORK|KDEBUG_INFO, "found %d results\n", count);

	for (int i = 0; i < count; i++)
	{
		Contact result;

		GaduContactAccountData *gcad = new GaduContactAccountData(result, Protocol->account(),
				gg_pubdir50_get(res, i, GG_PUBDIR50_UIN));

		result.addAccountData(gcad);
		result.setFirstName(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_FIRSTNAME)));
		result.setLastName(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_LASTNAME)));
		result.setNickName(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_NICKNAME)));
		result.setBirthYear(QString::fromAscii(gg_pubdir50_get(res, i, GG_PUBDIR50_BIRTHYEAR)).toUShort());
		result.setCity(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_CITY)));
		result.setFamilyName(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_FAMILYNAME)));
		result.setFamilyCity(cp2unicode(gg_pubdir50_get(res, i, GG_PUBDIR50_FAMILYCITY)));
		result.setGender((ContactData::ContactGender)QString::fromAscii(gg_pubdir50_get(res, i, GG_PUBDIR50_GENDER)).toUShort());
		// TODO: 0.6.6
		// result.setStatus(gg_pubdir50_get(res, 0, GG_PUBDIR50_STATUS));

		results.append(result);
	}

	From = gg_pubdir50_next(res);

	emit newResults(results);
}
Exemplo n.º 2
0
uint32 CRoutingZone::GetBootstrapContacts(ContactList *plistResult, uint32 uMaxRequired)
{
	ASSERT(m_pSuperZone == NULL);
	plistResult->clear();
	uint32 uRetVal = 0;
	try
	{
		ContactList top;
		TopDepth(LOG_BASE_EXPONENT, &top);
		if (top.size() > 0)
		{
			for (ContactList::const_iterator itContactList = top.begin(); itContactList != top.end(); ++itContactList)
			{
				plistResult->push_back(*itContactList);
				uRetVal++;
				if (uRetVal == uMaxRequired)
					break;
			}
		}
	}
	catch (...)
	{
		AddDebugLogLine(false, _T("Exception in CRoutingZone::getBoostStrapContacts"));
	}
	return uRetVal;
}
Exemplo n.º 3
0
ContactList* ContactTools::getFormedNativeContacts(ContactList* nativeContacts, Structure* comparisonStructure, double maxDistanceDeviation)
{
    // Get the sequence distance for each formed native contact.
    ContactList* formedNativeContacts = new ContactList;
    int i;
    for (i=0; i<nativeContacts->getNumberContacts(); i++)
    {
        Contact* nativeContact = nativeContacts->getContact(i);
        double nativeDistance = nativeContact->getContactDistance();
        
        // Find the contact in the comparison structure.
        Contact* comparisonContact = new Contact(comparisonStructure, nativeContact->getResidue1Index(), nativeContact->getAtom1Index(), nativeContact->getResidue2Index(), nativeContact->getAtom2Index());
        double comparisonDistance = comparisonContact->getContactDistance();
        
        if (nativeDistance-maxDistanceDeviation <= comparisonDistance && comparisonDistance <= nativeDistance+maxDistanceDeviation)
        {
            formedNativeContacts->addContact(comparisonContact);
        }
        else
        {
            // Otherwise delete the contact.
            delete comparisonContact;
            comparisonContact = NULL;
        }
    }
    
    return formedNativeContacts;
}
void SipRedirectorPresenceRouting::removeNonVoicemailContacts( ContactList& contactList )
{
   // walk the list to find the contact entry for voicemail
   size_t index;
   Url contactUrl;
   bool bVoicemailContactFound = false;
   for( index = 0; index < contactList.entries(); index++ )
   {
      if( contactList.get( index, contactUrl ) )
      {
         UtlString userPart;
         contactUrl.getUserId( userPart );
         if( userPart.index( VOICEMAIL_CONTACT_PREFIX ) == 0 )
         {
            bVoicemailContactFound = true;
            break;
         }
      }
   }

   // if vm contact found, remove all and put vm contact back in.
   if( bVoicemailContactFound )
   {
      contactList.removeAll( *this );
      contactList.add( contactUrl, *this );
   }
}
Exemplo n.º 5
0
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    ConfigurationStorage *config = ConfigurationStorage::instance();

    RSAKeyPair hostPair;

    QString keyName = config->getKeyName();

    if(!QFile::exists(keyName)) {
        if(!hostPair.generate(1024))
            Log::fatal("cannot generate new RSA keypair");

        if(!hostPair.writeToFile(keyName))
            Log::fatal("cannot write new RSA keypair");
    } else {
        if(!hostPair.readFromFile(keyName))
            Log::fatal("cannot read RSA keypair");
    }

    Router router;
    UdpPacketTransport transport(QHostAddress::Any, config->port());
    LinkLayer linkLayer(router, transport, hostPair);

    linkLayer.connect(&app, SIGNAL(aboutToQuit()), SLOT(exitNetwork()));

    ContactList contactList;
    MessagingApplicationLayer appLayer(contactList, linkLayer);
    Roster roster(contactList, linkLayer, appLayer);

    contactList.load();
    roster.show();

    return app.exec();
}
Exemplo n.º 6
0
ContactList* ContactList::getSubsetExcluding(ContactList* excludeList)
{
   int i, j;
    ContactList* newList = new ContactList();
    for (i=0; i<getNumberContacts(); i++)
    {
        bool include = true;
        Contact* contact = getContact(i);
        for (j=0; j<excludeList->getNumberContacts(); j++)
        {
            if (*contact == *excludeList->getContact(j))
            {
                include = false;
                break;
            }
        }
        
        // If this contact should be included, add it to the list.
        if (include)
        {
            newList->addContact(new Contact(*contact));
        }
    }
    
    return newList;
}
Exemplo n.º 7
0
 virtual RedirectPlugin::LookUpStatus lookUp(
    const SipMessage& message,
    const UtlString& requestString,
    const Url& requestUri,
    const UtlString& method,
    ContactList& contactList,
    RequestSeqNo requestSeqNo,
    int redirectorNo,
    SipRedirectorPrivateStorage*& privateStorage,
    ErrorDescriptor& errorDescriptor)
 {
    char diagMessage[100];
    sprintf( diagMessage, "%s::lookUp: contactList Size=%d", mLogName.data(), contactList.entries() );
    globalList.push_back( diagMessage );
    if( mBehavior.compareTo("ADD_SELF_AS_CONTACT") == 0 )
    {
       contactList.add( mLogName, *this );
       return RedirectPlugin::SUCCESS;
    }
    else if( mBehavior.compareTo("DONT_ADD_CONTACT") == 0 )
    {
       return RedirectPlugin::SUCCESS;
    }
    else if( mBehavior.compareTo("RETURN_ERROR") == 0 )
    {
       return RedirectPlugin::ERROR;
    }
    return RedirectPlugin::SUCCESS;
 }
Exemplo n.º 8
0
/**
 * Calculates thecontacts in a structure.
 *
 * @param structure The structure.
 * @param distanceCutoff The maximum distance between two residues from them to be considered in contact.
 * @param minSequenceDistance The minimum separation in the sequence for two residues to be considered contacts.
 * @param maxSequenceDistance The maximum separation in the sequence for two residues to be considered contacts.
 * @return The contacts present in the structure.
 */
ContactList* ContactTools::getContacts(Structure* structure, double distanceCutoff, int minSequenceDistance, int maxSequenceDistance)
{
    // Find all of the contacts within the cutoff distance.
    ContactList* contacts = new ContactList;
    int length = structure->getSize();
    int i, j, k, l;
    for (i=0; i<length-minSequenceDistance; i++)
    {
        int maxJ = length;
        if (maxSequenceDistance >= 0)
        {
            maxJ = i+maxSequenceDistance+1;
            if (maxJ > length) maxJ = length;
        }
            
        for (j=i+minSequenceDistance; j<maxJ; j++)
        {
            Residue* residue1 = structure->getResidue(i);
            Residue* residue2 = structure->getResidue(j);
            
            // If this is the same residue, process each atom pair only once.
            if (i == j)
            {
                for (k=0; k<residue1->getNumberAtoms()-1; k++)
                {
                    Atom* atom1 = residue1->getAtom(k);
                    for (l=k+1; l<residue2->getNumberAtoms(); l++)
                    {
                        Atom* atom2 = residue2->getAtom(l);
                        if (atom1->getDistanceTo(*atom2) <= distanceCutoff)
                        {
                            contacts->addContact(new Contact(structure, i, k, j, l));
                        }
                    }
                }
            }
            
            // Otherwise, process each atom pair.
            else
            {
                for (k=0; k<residue1->getNumberAtoms(); k++)
                {
                    Atom* atom1 = residue1->getAtom(k);
                    for (l=0; l<residue2->getNumberAtoms(); l++)
                    {
                        Atom* atom2 = residue2->getAtom(l);
                        if (atom1->getDistanceTo(*atom2) <= distanceCutoff)
                        {
                            contacts->addContact(new Contact(structure, i, k, j, l));
                        }
                    }
                }
            }
        }
    }
    
    return contacts;
}
Exemplo n.º 9
0
void RoutingBin::GetEntries(ContactList &outList, bool bEmptyFirst)
{
	if(bEmptyFirst)
		outList.clear();
	if(nodeList.size() > 0)
	{
		outList.insert(outList.end(),nodeList.begin(),nodeList.end());
	}
}
Exemplo n.º 10
0
/**
 * Calculates the fraction of native contacts between two structures.
 *
 * @param nativeContacts The native contacts.
 * @param comparisonStructure The structure to compare to the native.
 * @param distanceCutoff The maximum distance between two residues from them to be considered in contact.
 * @param minSequenceDistance The minimum separation in the sequence for two residues to be considered native.
 * @return The fraction of native contacts present in the comparison structure.
 */
double ContactTools::getFractionNativeContacts(ContactList* nativeContacts, Structure* comparisonStructure, double maxDistanceDeviation)
{
    if (nativeContacts->getNumberContacts() == 0) return 0.0;
    
    // Get the formed native contacts.
    ContactList* formedNativeContacts = getFormedNativeContacts(nativeContacts, comparisonStructure, maxDistanceDeviation);
    
    // Return the fraction.
    return double(formedNativeContacts->getNumberContacts())/double(nativeContacts->getNumberContacts());
}
Exemplo n.º 11
0
ContactList CsvXXPort::importContacts() const
{
    ContactList contactList;
    QPointer<CSVImportDialog> dlg = new CSVImportDialog(parentWidget());
    if (dlg->exec() && dlg) {
        contactList.setAddressList(dlg->contacts());
    }

    delete dlg;
    return contactList;
}
Exemplo n.º 12
0
ContactList LDAPXXPort::importContacts() const
{
    ContactList contactList;
    QPointer<KLDAP::LdapSearchDialog> dlg = new KLDAP::LdapSearchDialog(parentWidget());

    if (dlg->exec() && dlg) {
        contactList.setAddressList(dlg->selectedContacts());
    }

    delete dlg;
    return contactList;
}
Exemplo n.º 13
0
void CRoutingZone::WriteFile()
{
	// don't overwrite a bootstrap nodes.dat with an empty one, if we didn't finished probing
	if (!CKademlia::s_liBootstapList.IsEmpty() && GetNumContacts() == 0){
		DebugLogWarning(_T("Skipped storing nodes.dat, because we have an unfinished bootstrap of the nodes.dat version and no contacts in our routing table"));
		return;
	}
	try
	{
		// Write a saved contact list.
		CUInt128 uID;
		CSafeBufferedFile file;
		CFileException fexp;
		if (file.Open(m_sFilename, CFile::modeWrite | CFile::modeCreate | CFile::typeBinary|CFile::shareDenyWrite, &fexp))
		{
			setvbuf(file.m_pStream, NULL, _IOFBF, 32768);

			// The bootstrap method gets a very nice sample of contacts to save.
			ContactList listContacts;
			GetBootstrapContacts(&listContacts, 200);
			// Start file with 0 to prevent older clients from reading it.
			file.WriteUInt32(0);
			// Now tag it with a version which happens to be 2 (1 till 0.48a).
			file.WriteUInt32(2);
			// file.WriteUInt32(0) // if we would use version >=3, this would mean that this is a normal nodes.dat
			file.WriteUInt32((uint32_t)listContacts.size());
			for (ContactList::const_iterator itContactList = listContacts.begin(); itContactList != listContacts.end(); ++itContactList)
			{
				CContact* pContact = *itContactList;
				pContact->GetClientID(&uID);
				file.WriteUInt128(&uID);
				file.WriteUInt32(pContact->GetIPAddress());
				file.WriteUInt16(pContact->GetUDPPort());
				file.WriteUInt16(pContact->GetTCPPort());
				file.WriteUInt8(pContact->GetVersion());
				pContact->GetUDPKey().StoreToFile(file);
				file.WriteUInt8(pContact->IsIpVerified() ? 1 : 0);
			}
			file.Close();
			AddDebugLogLine( false, _T("Wrote %ld contact%s to file."), listContacts.size(), ((listContacts.size() == 1) ? _T("") : _T("s")));
		}
		else
			DebugLogError(_T("Unable to store Kad file: %s"), m_sFilename);
	}
	catch (CFileException* e)
	{
		e->Delete();
		AddDebugLogLine(false, _T("CFileException in CRoutingZone::writeFile"));
	}
}
Exemplo n.º 14
0
void ContactCluster::sList()
{
    ContactList* newdlg = new ContactList(this);
    if (newdlg)
    {
	int id = newdlg->exec();
	setId(id);
    }
    else
	QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				      .arg(__FILE__)
				      .arg(__LINE__),
			      tr("Could not instantiate a List Dialog"));
}
Exemplo n.º 15
0
bool CsvXXPort::exportContacts(const ContactList &contacts, VCardExportSelectionWidget::ExportFields) const
{
    QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QStringLiteral("addressbook.csv")));
    if (url.isEmpty()) {
        return true;
    }

    if (QFileInfo(url.isLocalFile() ? url.toLocalFile() : url.path()).exists()) {
        if (url.isLocalFile() && QFileInfo(url.toLocalFile()).exists()) {
            PimCommon::RenameFileDialog::RenameFileDialogResult result = PimCommon::RenameFileDialog::RENAMEFILE_IGNORE;
            PimCommon::RenameFileDialog *dialog = new PimCommon::RenameFileDialog(url, false, parentWidget());
            result = static_cast<PimCommon::RenameFileDialog::RenameFileDialogResult>(dialog->exec());
            if (result == PimCommon::RenameFileDialog::RENAMEFILE_RENAME) {
                url = dialog->newName();
            } else if (result == PimCommon::RenameFileDialog::RENAMEFILE_IGNORE) {
                delete dialog;
                return true;
            }
            delete dialog;
        }
    }

    if (!url.isLocalFile()) {
        QTemporaryFile tmpFile;
        if (!tmpFile.open()) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b></qt>", url.url());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&tmpFile, contacts.addressList());
        tmpFile.flush();
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite);
        KJobWidgets::setWindow(job, parentWidget());
        return job->exec();
    } else {
        QFile file(url.toLocalFile());
        if (!file.open(QIODevice::WriteOnly)) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b>.</qt>", url.toLocalFile());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&file, contacts.addressList());
        file.close();

        return true;
    }
}
Exemplo n.º 16
0
void ContactsTreeWidget::loadAvatars() {
  appInstance->logEvent("ContactsTreeWidget::loadAvatars()", SEVERITY_DEBUG);
  GroupList *gl = appInstance->mUser->getGroupList();
  ContactList *cl;
  ContactList::iterator c**t;
  GroupList::iterator glIt;
  for(glIt = gl->begin(); glIt != gl->end(); glIt++) {
    cl = glIt->second.contacts();
    for(c**t = cl->begin(); c**t != cl->end(); c**t++) {
      if (addedContacts[c**t->getIndex()]) {
        c**t->setAvatar(MrimUtils::prepareAvatar(c**t->getAddress()));
        addedContacts[c**t->getIndex()][columns.contactAvatar] = resizeAvatar(c**t->getAvatar());
      }
    }
  }
}
Exemplo n.º 17
0
void Flatland::Intersection::FindCircleCircle(const Geometry &g1, const Geometry &g2, ContactList &contacts)
{
    assert(g1.GetShape() == Shape::Circle);
    assert(g2.GetShape() == Shape::Circle);
    const Circle &c1 = static_cast<const Circle&>(g1);
    const Circle &c2 = static_cast<const Circle&>(g2);

    vec2 delta = c2.Center() - c1.Center();
    float radiusSum = c1.Radius() + c2.Radius();
    float distance = delta.length();
    if (distance > radiusSum)
        return;

    vec2 pos;
    vec2 normal;
    float depth;

    if (distance <= 0)
    {
        pos = c1.Center();
        normal = vec2(1, 0);
        depth = radiusSum;
    }
    else
    {
        normal = delta / distance;
        float k = 0.5 * (c2.Radius() - c1.Radius() - distance);
        pos = c1.Center() + normal * k;
        depth = radiusSum - distance;
    }

    contacts.AddContact(pos, -normal, depth);
}
Exemplo n.º 18
0
//---------------------------------------------------------------------------
void __fastcall TSingleLogFrame::ArchiveMatchTreeGetText(
   TBaseVirtualTree *Sender, PVirtualNode Node, TColumnIndex Column,
   TVSTTextType /*TextType*/, WideString &CellText )
{
   CellText = "";
   MatchNodeListData * pc = ( MatchNodeListData * ) Sender->GetNodeData( Node );
   ContactList *clp = pc->matchedList;
   if ( pc && ( clp || pc->matchedContact ) && Column >= 0 )
   {
      if ( pc->top )
      {
         if ( Column == 0 )
            CellText = ( clp->name ).c_str();
      }
      else
      {
         std::string cell;
         BaseContestLog * ct = TContestApp::getContestApp() ->getCurrentContest();
         if ( ArchiveMatchTreeColumns[ Column ].fieldId == egComments )
         {
            std::string exch;
            clp->getMatchField( pc->matchedContact, egExchange, exch, ct );
            std::string cmnt;
            clp->getMatchField( pc->matchedContact, egComments, cmnt, ct );
            if ( exch.size() )
            {
               cell = exch + "(" + cmnt + ")";
            }
            else
            {
               cell = cmnt;
            }
         }
         else
         {
            clp->getMatchField( pc->matchedContact, ArchiveMatchTreeColumns[ Column ].fieldId, cell, ct );     // col 0 is the tree lines
         }
         CellText = cell.c_str();
      }
   }
   else
   {
      if ( Column == 0 )
         CellText = "No archive matches";
   }
}
Exemplo n.º 19
0
RedirectPlugin::LookUpStatus
SipRedirectorGateway::lookUp(
   const SipMessage& message,
   const UtlString& requestString,
   const Url& requestUri,
   const UtlString& method,
   ContactList& contactList,
   RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   ErrorDescriptor& errorDescriptor)
{
   UtlString userId;
   requestUri.getUserId(userId);
   OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp "
                 "userId = '%s'",
                 mLogName.data(), userId.data());

   // Test for the presence of the prefix.
   const char* user = userId.data();
   int prefix_length = mPrefix.length();
   // Compare the prefix.
   if (strncmp(user, mPrefix.data(), prefix_length) == 0)
   {
      // Extract the full routing prefix.
      UtlString routing_prefix(userId.data(), prefix_length + mDigits);

      // Look up the routing prefix in the map.
      mMapLock.acquire();
      UtlContainable* value = mMapUserToContacts.findValue(&routing_prefix);
      if (value)
      {
         // Have to make a copy of the string, as the map entry might get
         // changed later.
         UtlString hostpart(*(dynamic_cast <UtlString*> (value)));

         mMapLock.release();

         if (!hostpart.isNull())
         {            
            // Add the contact.
            UtlString s("sip:");
            s.append(hostpart);
            Url uri(s);
            // The remainder of userId becomes the userId to the gateway.
            uri.setUserId(&userId.data()[prefix_length + mDigits]);
            // Add the contact.
            contactList.add( uri, *this );
         }
      }
      else
      {
         mMapLock.release();
      }
   }

   return RedirectPlugin::SUCCESS;
}
Exemplo n.º 20
0
void CRoutingZone::Split()
{
	StopTimer();

	m_pSubZones[0] = GenSubZone(0);
	m_pSubZones[1] = GenSubZone(1);

	ContactList listEntries;
	m_pBin->GetEntries(&listEntries);
	for (ContactList::const_iterator itContactList = listEntries.begin(); itContactList != listEntries.end(); ++itContactList)
	{
		int iSuperZone = (*itContactList)->m_uDistance.GetBitNumber(m_uLevel);
		m_pSubZones[iSuperZone]->m_pBin->AddContact(*itContactList);
	}
	m_pBin->m_bDontDeleteContacts = true;
	delete m_pBin;
	m_pBin = NULL;
}
Exemplo n.º 21
0
void ContactWidget::sList()
{
  ContactList* newdlg = new ContactList(this);
  if (newdlg)
  {
    ParameterList params;
    params.append("searchAcctId", _searchAcctId);
    newdlg->set(params);
    int id = newdlg->exec();
    if (id > 0)
      setId(id);
  }
  else
    QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__),
                          tr("Could not instantiate a List Dialog"));
}
Exemplo n.º 22
0
void WPclient::SignalServerContactEvent(ServerBasedContactEvent* ev) {
    log_debug(ZONE,"Got server based contact list, importing");
    ContactList l = ev->getContactList();
    ContactList::iterator curr = l.begin();
    while (curr != l.end()) {
      contact c = it_contact_get(sesja,(*curr)->getUIN());
      if (c == NULL) {
        /* new contact not yet in our list */
        c = it_contact_add(sesja,(*curr)->getUIN());
        if(c != NULL)
          it_contact_subscribe(c,(*curr)->getAlias().c_str());
        log_debug(ZONE,"Imported UIN %ul", (*curr)->getUIN());
      } else
        log_debug(ZONE,"Skipped UIN %ul (already in list)", (*curr)->getUIN());
      ++curr;
    }
    log_debug(ZONE,"Finished import");
}
Exemplo n.º 23
0
void CRoutingZone::Split()
{
    StopTimer();

    m_subZones[0] = GenSubZone(0);
    m_subZones[1] = GenSubZone(1);

    ContactList entries;
    m_bin->GetEntries(&entries);
    m_bin->m_dontDeleteContacts = true;
    delete m_bin;
    m_bin = NULL;

    for (ContactList::const_iterator it = entries.begin(); it != entries.end(); ++it) {
        if (!m_subZones[(*it)->GetDistance().GetBitNumber(m_level)]->m_bin->AddContact(*it)) {
            delete *it;
        }
    }
}
Exemplo n.º 24
0
void ContactClusterLineEdit::sList()
{
  ContactList* newdlg = listFactory();
  if (newdlg)
  {
    ParameterList params;
    params.append("titlePlural", tr("Contacts"));
    if (_searchAcctId != -1)
      params.append("searchAcctId", _searchAcctId);
    newdlg->set(params);
    int id = newdlg->exec();
    setId(id);
  }
  else
    QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__),
                          tr("Could not instantiate a List Dialog"));
}
Exemplo n.º 25
0
void ContactList::compareWith(ContactList &pairList)
{
    for (int i=0; i<pairList.count(); i++)
        pairList[i].pairState = ContactItem::PairNotFound;
    for (int i=0; i<count(); i++) {
        ContactItem& item = (*this)[i];
        item.pairState = ContactItem::PairNotFound;
        item.pairItem = 0;
        // At first, search complete matching
        for(int j=0; j<pairList.count(); j++) {
            ContactItem& candidate = pairList[j];
            if (item.identicalTo(candidate)) {
                item.pairState = ContactItem::PairIdentical;
                item.pairItem = &candidate;
                item.pairIndex = j;
                candidate.pairItem = &item;
                candidate.pairState = ContactItem::PairIdentical;
                candidate.pairIndex = i;
                break;
            }
        }
        // If no identical records, search similar
        if (item.pairState==ContactItem::PairNotFound)
            for (int j=1; j<=MAX_COMPARE_PRIORITY_LEVEL; j++) {
                bool pairFound = false;
                for(int k=0; k<pairList.count(); k++) {
                    ContactItem& candidate = pairList[k];
                    if (item.similarTo(candidate, j)) {
                        pairFound = true;
                        item.pairState = ContactItem::PairSimilar;
                        item.pairItem = &candidate;
                        item.pairIndex = k;
                        candidate.pairItem = &item;
                        candidate.pairState = ContactItem::PairSimilar;
                        candidate.pairIndex = i;
                        break;
                    }
                }
                if (pairFound) break;
            }
    }
}
Exemplo n.º 26
0
void CRoutingZone::WriteFile()
{
	try
	{
		// Write a saved contact list.
		CUInt128 uID;
		//CSafeBufferedFile file;
		CBufferedFileIO file;
		CFileException fexp;
		if (file.Open(m_sFilename, CFile::modeWrite | CFile::modeCreate | CFile::typeBinary|CFile::shareDenyWrite, &fexp))
		{
			setvbuf(file.m_pStream, NULL, _IOFBF, 32768);

			// The bootstrap method gets a very nice sample of contacts to save.
			ContactList listContacts;
			GetBootstrapContacts(&listContacts, 200);
			// Start file with 0 to prevent older clients from reading it.
			file.WriteUInt32(0);
			// Now tag it with a version which happens to be 1.
			file.WriteUInt32(1);
			file.WriteUInt32((uint32)listContacts.size());
			for (ContactList::const_iterator itContactList = listContacts.begin(); itContactList != listContacts.end(); ++itContactList)
			{
				CContact* pContact = *itContactList;
				pContact->GetClientID(&uID);
				file.WriteUInt128(&uID);
				file.WriteUInt32(pContact->GetIPAddress());
				file.WriteUInt16(pContact->GetUDPPort());
				file.WriteUInt16(pContact->GetTCPPort());
				file.WriteUInt8(pContact->GetVersion());
			}
			file.Close();
			//AddDebugLogLine( false, _T("Wrote %ld contact%s to file."), listContacts.size(), ((listContacts.size() == 1) ? _T("") : _T("s")));
			TRACE(_T("Wrote %ld contact%s to file.\n"), listContacts.size(), ((listContacts.size() == 1) ? _T("") : _T("s")));
		}
	}
	catch (CFileException* e)
	{
		e->Delete();
		AddDebugLogLine(false, _T("CFileException in CRoutingZone::writeFile"));
	}
}
Exemplo n.º 27
0
RedirectPlugin::LookUpStatus
SipRedirectorUserParam::lookUp(
   const SipMessage& message,
   const UtlString& requestString,
   const Url& requestUri,
   const UtlString& method,
   ContactList& contactList,
   RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   ErrorDescriptor& errorDescriptor)
{
   if (mStripAll)
   {
      if (SipRedirectServer::getInstance()->sipUserAgent()->isMyHostAlias(requestUri))
      {
         UtlString userpart;
         requestUri.getUserId(userpart);

         ssize_t semiColonIndex;
         if ((semiColonIndex = userpart.index(';')) != UTL_NOT_FOUND)
         {
            UtlString strippedUser(userpart);
            strippedUser.remove(semiColonIndex);

            Url strippedUrl(requestUri);
            strippedUrl.setUserId(strippedUser);

            OsSysLog::add(FAC_SIP, PRI_INFO,
                          "%s::lookUp stripped parameters from '%s' -> '%s'",
                          mLogName.data(), userpart.data(), strippedUser.data());

            contactList.add(strippedUrl, *this);
         }
      }
      else
      {
         if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG))
         {
            UtlString logUri;
            requestUri.getUri(logUri);
            OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp '%s' not in my domain - not modified",
                          mLogName.data(), logUri.data());
         }
      }
   }
   else
   {
      OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp disabled by configuration",
                    mLogName.data());
   }

   return RedirectPlugin::SUCCESS;
}
Exemplo n.º 28
0
SipRedirector::LookUpStatus
SipRedirectorMPT::lookUp(
   const SipMessage& message,
   const UtlString& requestString,
   const Url& requestUri,
   const UtlString& method,
   ContactList& contactList,
   RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   ErrorDescriptor& errorDescriptor)
{
   UtlString userId;
   requestUri.getUserId(userId);
   OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp "
                 "userId = '%s'", mLogName.data(),
                 userId.data());

   // Look up the user ID in the map.
   mMapLock.acquire();
   UtlContainable* v = mMapUserToContacts.findValue(&userId);
   mMapLock.release();
   // If found, add the contacts.
   if (v)
   {
      // Extract all the contacts out of the contact string.
      const char* s;
      const char* s1;
      for (s = (dynamic_cast<UtlString*> (v))->data();
           *s != '\0';
           s = s1+1)
      {
         // Find the ending newline, if any.
         // (Beware that Tiny XML trims trailing newlines off text contents!)
         s1 = strchr(s, '\n');
         if (!s1)
         {
            s1 = s + strlen(s);
         }
         // Ignore it if it is null
         if (s1-s != 0)
         {
            // Construct a UtlString of this contact.
            UtlString c(s, s1-s);
            // Construct a Url of this contact.
            Url url(c.data(), FALSE);
            // Add the contact.
            contactList.add( url, *this );
         }
      }
   }

   return SipRedirector::SUCCESS;
}
Exemplo n.º 29
0
uint32_t CRoutingZone::GetBootstrapContacts(ContactList *results, uint32_t maxRequired) const
{
    ASSERT(m_superZone == NULL);

    results->clear();

    uint32_t count = 0;
    ContactList top;
    TopDepth(LOG_BASE_EXPONENT, &top);
    if (top.size() > 0) {
        for (ContactList::const_iterator it = top.begin(); it != top.end(); ++it) {
            results->push_back(*it);
            count++;
            if (count == maxRequired) {
                break;
            }
        }
    }

    return count;
}
RedirectPlugin::LookUpStatus
SipRedirectorPresenceRouting::doLookUp(
   const Url& toUrl,
   ContactList& contactList)
{
   // check if we have unified presence info for this user
   const UnifiedPresence* pUp;
   UtlString to;
   UtlString username;
   toUrl.getIdentity( to );
   toUrl.getUserId( username );
   OsSysLog::add(FAC_SIP, PRI_INFO, "%s::LookUpStatus is looking up '%s'",
                                    mLogName.data(),to.data() );
   pUp = UnifiedPresenceContainer::getInstance()->lookup( &to );

   if( pUp )
   {
      // unified presence data is available for the called party.
      // Use it to make call routing decisions.
       OsSysLog::add(FAC_SIP, PRI_INFO, "%s::LookUpStatus "
                                        "Presence information for '%s':\r\n"
                                        "    Telephony presence: '%s'"
                                        "    XMPP presence: '%s'"
                                        "    Custom presence message: '%s'",
                                        mLogName.data(),
                                        to.data(), pUp->getSipState().data(),
                                        pUp->getXmppPresence().data(),
                                        pUp->getXmppStatusMessage().data() );

       // look for tel uri in the custom presence message

       RegEx telUri( TelUri );
       telUri.Search( pUp->getXmppStatusMessage().data() );
       UtlString targetUri;
       if( telUri.MatchString( &targetUri, 1 ) )
       {
         // prepend 'sip:' and add target as contact
         targetUri.insert( 0, "sip:" );
         contactList.add( targetUri, *this );
      }
      else
      {
         // If user is busy then call goes directly to voicemail.
         if( ( pUp->getSipState().compareTo("BUSY", UtlString::ignoreCase ) == 0 && mbForwardToVmOnBusy ) ||
             ( pUp->getXmppPresence().compareTo("BUSY", UtlString::ignoreCase ) == 0 && mUserPrefs.forwardToVoicemailOnDnd( username ) ) )
         {
            // prune all non-voicemail contacts from the list
            removeNonVoicemailContacts( contactList );
         }
      }
   }
   return RedirectPlugin::SUCCESS;
}