Ejemplo n.º 1
0
Kopete::Contact *JabberProtocol::deserializeContact (Kopete::MetaContact * metaContact,
										 const QMap < QString, QString > &serializedData, const QMap < QString, QString > & /* addressBookData */ )
{
//  kdDebug (JABBER_DEBUG_GLOBAL) << k_funcinfo << "Deserializing data for metacontact " << metaContact->displayName () << "\n" << endl;

	QString contactId = serializedData["contactId"];
	QString displayName = serializedData["displayName"];
	QString accountId = serializedData["accountId"];
	QString jid = serializedData["JID"];

	QDict < Kopete::Account > accounts = Kopete::AccountManager::self ()->accounts (this);
	Kopete::Account *account = accounts[accountId];
	
	if (!account)
	{
		kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "WARNING: Account for contact does not exist, skipping." << endl;
		return 0;
	}
	
	JabberTransport *transport = dynamic_cast<JabberTransport*>(account);
	if( transport )
		transport->account()->addContact ( jid.isEmpty() ? contactId : jid ,  metaContact);
	else
		account->addContact (contactId,  metaContact);
	return account->contacts()[contactId];
}
void KopeteAccountConfig::slotColorChanged()
{
	if(m_protected)  //this slot is called because we changed the button
		return;      // color because another account has been selected

	KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() );
	if ( !lvi || !lvi->account() )
		return;
	Kopete::Account *account = lvi->account();

	if(!account->color().isValid() && !m_view->mUseColor->isChecked() )
	{  //we don't use color for that account and nothing changed.
		m_newColors.remove(account);
		return;
	}
	else if(!m_view->mUseColor->isChecked())
	{  //the user disabled account coloring, but it was activated before
		m_newColors[account]=QColor();
		emit changed(true);
		return;
	}
	else if(account->color() == m_view->mColorButton->color() )
	{   //The color has not changed.
		m_newColors.remove(account);
		return;
	}
	else
	{
		m_newColors[account]=m_view->mColorButton->color();
		emit changed(true);
	}
}
void KopeteAccountConfig::slotItemSelected()
{
	m_protected=true;
	KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() );

	m_view->mButtonEdit->setEnabled( itemSelected );
	m_view->mButtonRemove->setEnabled( itemSelected );

	if ( itemSelected &&  itemSelected->account() )
	{
		m_view->mButtonUp->setEnabled( itemSelected->itemAbove() );
		m_view->mButtonDown->setEnabled( itemSelected->itemBelow() );

		Kopete::Account *account = itemSelected->account();
		QColor color= m_newColors.contains(account) ? m_newColors[account] :  account->color();
		m_view->mUseColor->setEnabled( true );
		m_view->mUseColor->setChecked( color.isValid() );
		m_view->mColorButton->setColor( color );
		m_view->mColorButton->setEnabled( m_view->mUseColor->isChecked() );

	}
	else
	{
		m_view->mButtonUp->setEnabled( false );
		m_view->mButtonDown->setEnabled( false);
		m_view->mUseColor->setEnabled( false );
		m_view->mColorButton->setEnabled( false );
	}
	m_protected=false;
}
Ejemplo n.º 4
0
void KopeteApplication::slotAllPluginsLoaded()
{
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	// --noconnect not specified?
	if ( args->isSet( "connect" )  && KopetePrefs::prefs()->autoConnect() )
		Kopete::AccountManager::self()->connectAll();


	// Handle things like '--autoconnect foo,bar --autoconnect foobar'
	KStringList connectArgsC = args->getOptionList( "autoconnect" );
	QStringList connectArgs;

	for ( KStringList::ConstIterator it = connectArgsC.begin(); it != connectArgsC.end(); ++it )
	{
		QStringList split = QStringList::split( ',', QString::fromLatin1( *it ) );

		for ( QStringList::ConstIterator it2 = split.begin(); it2 != split.end(); ++it2 )
		{
			connectArgs.append( *it2 );
		}
	}
	
	for ( QStringList::ConstIterator i = connectArgs.begin(); i != connectArgs.end(); ++i )
	{
		QRegExp rx( QString::fromLatin1( "([^\\|]*)\\|\\|(.*)" ) );
		rx.search( *i );
		QString protocolId = rx.cap( 1 );
		QString accountId = rx.cap( 2 );

		if ( accountId.isEmpty() )
		{
			if ( protocolId.isEmpty() )
				accountId = *i;
			else
				continue;
		}

		QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
		Kopete::Account *account;
		while ( ( account = it.current() ) != 0 )
		{
			++it;

			if ( ( account->accountId() == accountId ) )
			{
				if ( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
				{
					account->connect();
					break;
				}
			}
		}
	}

	// Parse any passed URLs/files
	handleURLArgs();
}
Ejemplo n.º 5
0
		AccountListViewItem(QListView *parent, Kopete::Account *acc)
			: KListViewItem(parent)
		{
			if (acc==0)
				return;

			/*kdDebug(14010) << k_funcinfo <<
				"account name = " << acc->accountId() << endl;*/
			mAccount = acc;
			setText(0, mAccount->accountId());
			setPixmap(0, mAccount->accountIcon());
		}
Ejemplo n.º 6
0
void AddAccountWizard::accept()
{
	// registeredAccount shouldn't probably be called here. Anyway, if the account is already registered, 
	// it won't be registered twice
	Kopete::AccountManager *manager = Kopete::AccountManager::self();
	Kopete::Account        *account = d->accountPage->apply();

	// if the account wasn't created correctly then leave
	if (!account)
	{
		reject();
		return;
	}

	// Set a valid identity before registering the account
	if (!d->identity)
	{
		account->setIdentity(Kopete::IdentityManager::self()->defaultIdentity());
	}
	else
	{
		account->setIdentity(d->identity);
	}

	account = manager->registerAccount(account);
	// if the account wasn't created correctly then leave
	if (!account)
	{
		reject();
		return;
	}

	// Make sure the protocol is correctly enabled.  This is not really needed, but still good
	const QString PROTO_NAME = d->proto->pluginId().remove("Protocol").toLower();
	Kopete::PluginManager::self()->setPluginEnabled(PROTO_NAME , true);

	// setup the custom colour
	if (d->uiFinish.mUseColor->isChecked())
	{
		account->setColor(d->uiFinish.mColorButton->color());
	}

	// connect if necessary
	if (d->uiFinish.mConnectNow->isChecked())
	{
		account->connect();
	}

	KAssistantDialog::accept();
}
Ejemplo n.º 7
0
QStringList KopeteIface::accounts()
{
    QStringList list;
    QPtrList<Kopete::Account> m_accounts=Kopete::AccountManager::self()->accounts();
    QPtrListIterator<Kopete::Account> it( m_accounts );
    Kopete::Account *account;
    while ( ( account = it.current() ) != 0 )
    {
        ++it;

        list += ( account->protocol()->pluginId() +"||" + account->accountId() );
    }

    return list;

}
Ejemplo n.º 8
0
void KopeteIface::disconnect(const QString &protocolId, const QString &accountId )
{
    QPtrListIterator<Kopete::Account> it( Kopete::AccountManager::self()->accounts() );
    Kopete::Account *account;
    while ( ( account = it.current() ) != 0 )
    {
        ++it;

        if( ( account->accountId() == accountId) )
        {
            if( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId )
            {
                account->disconnect();
                break;
            }
        }
    }
}
Ejemplo n.º 9
0
bool KopeteIface::addContact( const QString &protocolName, const QString &accountId, const QString &contactId,
                              const QString &displayName, const QString &groupName )
{
    //Get the protocol instance
    Kopete::Account *myAccount = Kopete::AccountManager::self()->findAccount( protocolName, accountId );

    if( myAccount )
    {
        QString contactName;
        Kopete::Group *realGroup=0L;
        //If the nickName isn't specified we need to display the userId in the prompt
        if( displayName.isEmpty() || displayName.isNull() )
            contactName = contactId;
        else
            contactName = displayName;

        if ( !groupName.isEmpty() )
            realGroup=Kopete::ContactList::self()->findGroup( groupName );

        // Confirm with the user before we add the contact
        // FIXME: This is completely bogus since the user may not
        // even be at the computer. We just need to add the contact --Matt
        if( KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n( "An external application is attempting to add the "
                                        " '%1' contact '%2' to your contact list. Do you want to allow this?" )
                                        .arg( protocolName ).arg( contactName ), i18n( "Allow Contact?" ), i18n("Allow"), i18n("Reject") ) == 3 ) // Yes == 3
        {
            //User said Yes
            myAccount->addContact( contactId, contactName, realGroup, Kopete::Account::DontChangeKABC);
            return true;
        } else {
            //User said No
            return false;
        }

    } else {
        //This protocol is not loaded
        KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Error,
                                       i18n("An external application has attempted to add a contact using "
                                            " the %1 protocol, which either does not exist or is not loaded.").arg( protocolName ),
                                       i18n("Missing Protocol"));

        return false;
    }
}
Ejemplo n.º 10
0
void KopeteAccountConfig::load()
{
	KopeteAccountLVI *lvi = 0L;

	m_view->mAccountList->clear();

	QPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();
	for ( Kopete::Account *i = accounts.first() ; i; i = accounts.next() )
	{
		// Insert the item after the previous one
		lvi = new KopeteAccountLVI( i, m_view->mAccountList );
		lvi->setText( 0, i->protocol()->displayName() );
		lvi->setPixmap( 0, i->accountIcon() );
		lvi->setText( 1, i->accountLabel() );
	}

	m_newColors.clear();
	slotItemSelected();
}
Ejemplo n.º 11
0
void KopeteAccountConfig::slotEditAccount()
{
	KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() );
	if ( !lvi || !lvi->account() )
		return;

	Kopete::Account *ident = lvi->account();
	Kopete::Protocol *proto = ident->protocol();

	KDialogBase *editDialog = new KDialogBase( this, "KopeteAccountConfig::editDialog", true,
		i18n( "Edit Account" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true );

	KopeteEditAccountWidget *m_accountWidget = proto->createEditAccountWidget( ident, editDialog );
	if ( !m_accountWidget )
		return;

	// FIXME: Why the #### is EditAccountWidget not a QWidget?!? This sideways casting
	//        is braindead and error-prone. Looking at MSN the only reason I can see is
	//        because it allows direct subclassing of designer widgets. But what is
	//        wrong with embedding the designer widget in an empty QWidget instead?
	//        Also, if this REALLY has to be a pure class and not a widget, then the
	//        class should at least be renamed to EditAccountIface instead - Martijn
	QWidget *w = dynamic_cast<QWidget *>( m_accountWidget );
	if ( !w )
		return;

	editDialog->setMainWidget( w );
	if ( editDialog->exec() == QDialog::Accepted )
	{
		if( m_accountWidget->validateData() )
			m_accountWidget->apply();
	}

	// FIXME: Why deleteLater? It shouldn't be in use anymore at this point - Martijn
	editDialog->deleteLater();
	load();
	Kopete::AccountManager::self()->save();
}
Ejemplo n.º 12
0
void KopeteAccountConfig::slotRemoveAccount()
{
	KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() );
	if ( !lvi || !lvi->account() )
		return;

	Kopete::Account *i = lvi->account();
	if ( KMessageBox::warningContinueCancel( this, i18n( "Are you sure you want to remove the account \"%1\"?" ).arg( i->accountLabel() ),
		i18n( "Remove Account" ), KGuiItem(i18n( "Remove Account" ), "editdelete"),
		 "askRemoveAccount", KMessageBox::Notify | KMessageBox::Dangerous ) == KMessageBox::Continue )
	{
		Kopete::AccountManager::self()->removeAccount( i );
		delete lvi;
	}
}
Ejemplo n.º 13
0
void HistoryPlugin::convertOldHistory()
{
	bool deleteFiles=  KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
		i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStdGuiItem::del(), i18n("Keep") ) == KMessageBox::Yes;

	KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , "history_progress_dlg" , i18n( "History converter" ) ,
		 QString::null , true); //modal  to  make sure the user will not doing stupid things (we have a kapp->processEvents())
	progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel


	QString kopetedir=locateLocal( "data", QString::fromLatin1( "kopete"));
	QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/

	d.setFilter( QDir::Dirs  );

	const QFileInfoList_qt3 *list = d.entryInfoList_qt3();
	QFileInfoListIterator it( *list );
	QFileInfo *fi;
	while ( (fi = it.current()) != 0 )
	{
		QString protocolId;
		QString accountId;

		if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi->fileName() ) ) )
		{
			protocolId=p->pluginId();
			QDictIterator<Kopete::Account> it(Kopete::AccountManager::self()->accounts(p));
			Kopete::Account *a = it.current();
			if(a)
				accountId=a->accountId();
		}

		if(accountId.isNull() || protocolId.isNull())
		{
			if(fi->fileName() == "MSNProtocol" || fi->fileName() == "msn_logs" )
			{
				protocolId="MSNProtocol";
				KGlobal::config()->setGroup("MSN");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "ICQProtocol" || fi->fileName() == "icq_logs" )
			{
				protocolId="ICQProtocol";
				KGlobal::config()->setGroup("ICQ");
				accountId=KGlobal::config()->readEntry( "UIN" );
			}
			else if(fi->fileName() == "AIMProtocol" || fi->fileName() == "aim_logs" )
			{
				protocolId="AIMProtocol";
				KGlobal::config()->setGroup("AIM");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "OscarProtocol" )
			{
				protocolId="AIMProtocol";
				KGlobal::config()->setGroup("OSCAR");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			else if(fi->fileName() == "JabberProtocol" || fi->fileName() == "jabber_logs")
			{
				protocolId="JabberProtocol";
				KGlobal::config()->setGroup("Jabber");
				accountId=KGlobal::config()->readEntry( "UserID" );
			}
			//TODO: gadu, wp
		}

		if(!protocolId.isEmpty() || !accountId.isEmpty())
		{
			QDir d2( fi->absFilePath() );
			d2.setFilter( QDir::Files  );
			d2.setNameFilter("*.log");
			const QFileInfoList_qt3 *list = d2.entryInfoList_qt3();
			QFileInfoListIterator it2( *list );
			QFileInfo *fi2;

			progressDlg->progressBar()->reset();
			progressDlg->progressBar()->setTotalSteps(d2.count());
			progressDlg->setLabel(i18n("Parsing old history in %1").arg(fi->fileName()));
			progressDlg->show(); //if it was not already showed...

			while ( (fi2 = it2.current()) != 0 )
			{
				//we assume that all "-" are dots.  (like in hotmail.com)
				QString contactId=fi2->fileName().replace(".log" , QString::null).replace("-" , ".");

				if(!contactId.isEmpty() )
				{
					progressDlg->setLabel(i18n("Parsing old history in %1:\n%2").arg(fi->fileName()).arg(contactId));
					kapp->processEvents(0); //make sure the text is updated in the progressDlg

					int month=0;
					int year=0;
					QDomDocument doc;
					QDomElement docElem;

					QDomElement msgelement;
					QDomNode node;
					QDomDocument xmllist;
					Kopete::Message::MessageDirection dir;
					QString body, date, nick;
					QString buffer, msgBlock;
					char cbuf[CBUFLENGTH]; // buffer for the log file

					QString logFileName = fi2->absFilePath();

					// open the file
					FILE *f = fopen(QFile::encodeName(logFileName), "r");

					// create a new <message> block
					while ( ! feof( f ) )
					{
						fgets(cbuf, CBUFLENGTH, f);
						buffer = QString::fromUtf8(cbuf);

						while ( strchr(cbuf, '\n') == NULL && !feof(f) )
						{
							fgets( cbuf, CBUFLENGTH, f );
							buffer += QString::fromUtf8(cbuf);
						}

						if( buffer.startsWith( QString::fromLatin1( "<message " ) ) )
						{
							msgBlock = buffer;

							// find the end of the message block
							while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ )
							{
								fgets(cbuf, CBUFLENGTH, f);
								buffer = QString::fromUtf8(cbuf);

								while ( strchr(cbuf, '\n') == NULL && !feof(f) )
								{
									fgets( cbuf, CBUFLENGTH, f );
									buffer += QString::fromUtf8(cbuf);
								}
								msgBlock.append(buffer);
							}

							// now let's work on this new block
							xmllist.setContent(msgBlock, false);
							msgelement = xmllist.documentElement();
							node = msgelement.firstChild();

							if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) )
								dir = Kopete::Message::Inbound;
							else
								dir = Kopete::Message::Outbound;

							// Read all the elements.
							QString tagname;
							QDomElement element;

							while ( ! node.isNull() )
							{
								if ( node.isElement() )
								{
									element = node.toElement();
									tagname = element.tagName();

									if( tagname == QString::fromLatin1( "srcnick" ) )
										nick = element.text();

									else if( tagname == QString::fromLatin1( "date" ) )
										date = element.text();
									else if( tagname == QString::fromLatin1( "body" ) )
										body = element.text().stripWhiteSpace();
								}

								node = node.nextSibling();
							}
							//FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.
							// so QT can't parse it correctly.
							QDateTime dt=QDateTime::fromString(date);
							if(dt.date().month() != month || dt.date().year() != year)
							{
								if(!docElem.isNull())
								{
									QDate date(year,month,1);
									QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											QString::fromLatin1( "/" ) +
											contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
											date.toString(".yyyyMM");
									KSaveFile file(  locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name+ QString::fromLatin1( ".xml" ) )  );
									if( file.status() == 0 )
									{
										QTextStream *stream = file.textStream();
										//stream->setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
										doc.save( *stream , 1 );
										file.close();
									}
								}


								month=dt.date().month();
								year=dt.date().year();
								docElem=QDomElement();
							}

							if(docElem.isNull())
							{
								doc=QDomDocument("Kopete-History");
								docElem= doc.createElement( "kopete-history" );
								docElem.setAttribute ( "version" , "0.7" );
								doc.appendChild( docElem );
								QDomElement headElem = doc.createElement( "head" );
								docElem.appendChild( headElem );
								QDomElement dateElem = doc.createElement( "date" );
								dateElem.setAttribute( "year",  QString::number(year) );
								dateElem.setAttribute( "month", QString::number(month) );
								headElem.appendChild(dateElem);
								QDomElement myselfElem = doc.createElement( "contact" );
								myselfElem.setAttribute( "type",  "myself" );
								myselfElem.setAttribute( "contactId", accountId  );
								headElem.appendChild(myselfElem);
								QDomElement contactElem = doc.createElement( "contact" );
								contactElem.setAttribute( "contactId", contactId );
								headElem.appendChild(contactElem);
								QDomElement importElem = doc.createElement( "imported" );
								importElem.setAttribute( "from",  fi->fileName() );
								importElem.setAttribute( "date", QDateTime::currentDateTime().toString()  );
								headElem.appendChild(importElem);
							}
							QDomElement msgElem = doc.createElement( "msg" );
							msgElem.setAttribute( "in",  dir==Kopete::Message::Outbound ? "0" : "1" );
							msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId  );
							msgElem.setAttribute( "nick",  nick ); //do we have to set this?
							msgElem.setAttribute( "time",  QString::number(dt.date().day()) + " " +  QString::number(dt.time().hour()) + ":" + QString::number(dt.time().minute())  );
							QDomText msgNode = doc.createTextNode( body.stripWhiteSpace() );
							docElem.appendChild( msgElem );
							msgElem.appendChild( msgNode );
						}
					}

					fclose( f );
					if(deleteFiles)
						d2.remove(fi2->fileName() , false);

					if(!docElem.isNull())
					{
						QDate date(year,month,1);
						QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								QString::fromLatin1( "/" ) +
								contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) +
								date.toString(".yyyyMM");
						KSaveFile file(  locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name+ QString::fromLatin1( ".xml" ) )  );
						if( file.status() == 0 )
						{
							QTextStream *stream = file.textStream();
							//stream->setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non?
							doc.save( *stream ,1 );
							file.close();
						}
					}

				}
				progressDlg->progressBar()->setProgress(progressDlg->progressBar()->progress()+1);
				++it2;
			}
		}
		++it;
	}
	delete progressDlg;

}
Ejemplo n.º 14
0
void NowListeningPlugin::slotAdvertCurrentMusic()
{
	// Do anything when statusAdvertising is off.
	if( !NowListeningConfig::self()->statusAdvertising() && !NowListeningConfig::self()->appendStatusAdvertising() )
		return; 

	// This slot is called every 5 seconds, so we check if we have a new track playing.
	if( newTrackPlaying() )
	{
		QString advert;

		QPtrList<Kopete::Account> accountsList = Kopete::AccountManager::self()->accounts();
		for( Kopete::Account* a = accountsList.first(); a; a = accountsList.next() )
		{
			/*
				NOTE:
				MSN status message(personal message) use a special tag to advert the current music playing. 
				So, we don't send the all formatted string, send a special string seperated by ";".
				
				Also, do not use MSN hack in appending mode.
			*/
			if( a->protocol()->pluginId() == "MSNProtocol" && !NowListeningConfig::self()->appendStatusAdvertising() )
			{
				QString track, artist, album, mediaList;
				bool isPlaying=false;

				if( NowListeningConfig::self()->useSpecifiedMediaPlayer() && d->m_currentMediaPlayer )
				{
					if( d->m_currentMediaPlayer->playing() )
					{
						track = d->m_currentMediaPlayer->track();
						artist = d->m_currentMediaPlayer->artist();
						album = d->m_currentMediaPlayer->album();
						mediaList = track + ";" + artist + ";" + album;
						isPlaying = true;
					}
				}
				else
				{
					for ( NLMediaPlayer* i = d->m_mediaPlayerList.first(); i; i = d->m_mediaPlayerList.next() )
					{
						if( i->playing() )
						{
							track = i->track();
							artist = i->artist();
							album = i->album();
							mediaList = track + ";" + artist + ";" + album;
							isPlaying = true;
						}
					}
				}

				// KDE4 TODO: Use the new status message framework, and remove this "hack".
				if( isPlaying )
				{
					advert = QString("[Music]%1").arg(mediaList);
				}

			}
			else
			{
				if( NowListeningConfig::self()->appendStatusAdvertising() )
				{
					// Check for the now listening message in parenthesis, 
					// include the header to not override other messages in parenthesis.
					QRegExp statusSong( QString(" \\(%1.*\\)$").arg( NowListeningConfig::header()) );
					
					// HACK: Don't keep appending the now listened song. Replace it in the status message.
					advert = a->myself()->property( Kopete::Global::Properties::self()->awayMessage() ).value().toString();
					// Remove the braces when they are no listened song.
					QString mediaAdvert = mediaPlayerAdvert(false);
					if(!mediaAdvert.isEmpty())
					{
						if(statusSong.search(advert) != -1)
						{
							advert = advert.replace(statusSong, QString(" (%1)").arg(mediaPlayerAdvert(false)) );
						}
						else
						{
							advert += QString(" (%1)").arg( mediaPlayerAdvert(false) );
						}
					}
					else
					{
						advert = advert.replace(statusSong, "");
					}
				}
				else
				{
					advert = mediaPlayerAdvert(false); // newTrackPlaying has done the update.
				}
			}

			a->setOnlineStatus(a->myself()->onlineStatus(), advert);
		}
	}
}
Ejemplo n.º 15
0
bool KABCPersistence::syncWithKABC( MetaContact * mc )
{
	kDebug(14010) ;
	bool contactAdded = false;
	// check whether the dontShowAgain was checked
		KABC::AddressBook* ab = addressBook();
		KABC::Addressee addr  = ab->findByUid( mc->kabcId() );

		if ( !addr.isEmpty() ) // if we are associated with KABC
		{
// load the set of addresses from KABC
		const QStringList customs = addr.customs();

		QStringList::ConstIterator it;
		for ( it = customs.constBegin(); it != customs.constEnd(); ++it )
		{
			QString app, name, value;
			splitField( *it, app, name, value );
			kDebug( 14010 ) << "app=" << app << " name=" << name << " value=" << value;

			if ( app.startsWith( QLatin1String( "messaging/" ) ) )
			{
				if ( name == QLatin1String( "All" ) )
				{
					kDebug( 14010 ) << " syncing \"" << app << ":" << name << " with contact list ";
					// Get the protocol name from the custom field
					// by chopping the 'messaging/' prefix from the custom field app name
					QString protocolName = app.right( app.length() - 10 );
					// munge Jabber hack
					if ( protocolName == QLatin1String( "xmpp" ) )
						protocolName = QLatin1String( "jabber" );

					// Check Kopete supports it
					Protocol * proto = dynamic_cast<Protocol*>( PluginManager::self()->loadPlugin( QLatin1String( "kopete_" ) + protocolName ) );
					if ( !proto )
					{
						KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
																					 i18n( "<qt>\"%1\" is not supported by Kopete.</qt>", protocolName ),
																					 i18n( "Could Not Sync with KDE Address Book" )  );
						continue;
					}

					// See if we need to add each contact in this protocol
					QStringList addresses = value.split( QChar( 0xE000 ), QString::SkipEmptyParts );
					QStringList::iterator end = addresses.end();
					for ( QStringList::iterator it = addresses.begin(); it != end; ++it )
					{
						// check whether each one is present in Kopete
						// Is it in the contact list?
						// First discard anything after an 0xE120, this is used by IRC to separate nick and server group name, but
						// IRC doesn't support this properly yet, so the user will have to select an appropriate account manually
						int separatorPos = (*it).indexOf( QChar( 0xE120 ) );
						if ( separatorPos != -1 )
							*it = (*it).left( separatorPos );

						Kopete::MetaContact *otherMc = 0;
						foreach( Kopete::Account *act, Kopete::AccountManager::self()->accounts() )
						{
							if( act->protocol() != proto )
								continue;
							Kopete::Contact *c= act->contacts().value(*it);
							if(c)
							{
								otherMc=c->metaContact();
								break;
							}
						}

						if ( otherMc ) // Is it in another metacontact?
						{
							// Is it already in this metacontact? If so, we needn't do anything
							if ( otherMc == mc )
							{
								kDebug( 14010 ) << *it << " already a child of this metacontact.";
								continue;
							}
							kDebug( 14010 ) << *it << " already exists in OTHER metacontact, move here?";
							// find the Kopete::Contact and attempt to move it to this metacontact.
							otherMc->findContact( proto->pluginId(), QString(), *it )->setMetaContact( mc );
						}
						else
						{
							// if not, prompt to add it
							kDebug( 14010 ) << proto->pluginId() << "://" << *it << " was not found in the contact list.  Prompting to add...";
							if ( KMessageBox::Yes == KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),
									 i18n( "<qt>An address was added to this contact by another application.<br />Would you like to use it in Kopete?<br /><b>Protocol:</b> %1<br /><b>Address:</b> %2</qt>", proto->displayName(), *it ), i18n( "Import Address From Address Book" ), KGuiItem( i18n("Use") ), KGuiItem( i18n("Do Not Use") ), QLatin1String( "ImportFromKABC" ) ) )
							{
								// Check the accounts for this protocol are all connected
								// Most protocols do not allow you to add contacts while offline
								// Would be better to have a virtual bool Kopete::Account::readyToAddContact()
								int accountcount=0;
								bool allAccountsConnected = true;
								Kopete::Account *chosen = 0;
								foreach( Kopete::Account *act, Kopete::AccountManager::self()->accounts() )
								{
									if( act->protocol() == proto) 
									{
										accountcount++;
										if(!act->isConnected())
										{
											allAccountsConnected=false;
											break;
										}
										chosen=act;
									}
								}

								if ( !allAccountsConnected )
								{
									KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>One or more of your accounts using %1 are offline.  Most systems have to be connected to add contacts.  Please connect these accounts and try again.</qt>", protocolName ),
											i18n( "Not Connected" )  );
									continue;
								}

								// we have got a contact to add, our accounts are connected, so add it.
								// Do we need to choose an account
								if ( accountcount > 1 )
								{	// if we have >1 account in this protocol, prompt for the protocol.
									KDialog *chooser = new KDialog(0);
									chooser->setCaption( i18n("Choose Account") );
									chooser->setButtons( KDialog::Ok | KDialog::Cancel );

									AccountSelector *accSelector = new AccountSelector(proto, chooser);
									accSelector->setObjectName( QLatin1String("accSelector") );
									chooser->setMainWidget(accSelector);
									if ( chooser->exec() == QDialog::Rejected )
										continue;
									chosen = accSelector->selectedItem();

									delete chooser;
								}
								else if ( accountcount == 0 )
								{
									KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>You do not have an account configured for <b>%1</b> yet.  Please create an account, connect it, and try again.</qt>", protocolName ),
											i18n( "No Account Found" )  );
									continue;
								}

								// add the contact to the chosen account
								if ( chosen )
								{
									kDebug( 14010 ) << "Adding " << *it << " to " << chosen->accountId();
									if ( chosen->addContact( *it, mc ) )
										contactAdded = true;
									else
										KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Sorry,
											i18n( "<qt>It was not possible to add the contact.</qt>" ),
											i18n( "Could Not Add Contact") ) ;
								}
							}
							else
								kDebug( 14010 ) << " user declined to add " << *it << " to contact list ";
						}
					}
					kDebug( 14010 ) << " all " << addresses.count() << " contacts in " << proto->pluginId() << " checked ";
				}
				else