summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/oscar/aim/aimcontact.cpp
blob: 0d42c8ce3a0f5b9bd4501279d60a1b0c586a55ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*
  aimcontact.cpp  -  Oscar Protocol Plugin

  Copyright (c) 2003 by Will Stephenson
  Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

  *************************************************************************
  *                                                                       *
  * This program is free software; you can redistribute it and/or modify  *
  * it under the terms of the GNU General Public License as published by  *
  * the Free Software Foundation; either version 2 of the License, or     *
  * (at your option) any later version.                                   *
  *                                                                       *
  *************************************************************************
*/

#include <time.h>

#include <tqimage.h>
#include <tqregexp.h>
#include <tqtimer.h>
#include <tqtextcodec.h>

#include <tdeapplication.h>
#include <tdeactionclasses.h>
#include <tdelocale.h>
#include <kdebug.h>
#include <tdemessagebox.h>

#include "kopeteaway.h"
#include "kopetechatsession.h"
#include "kopeteuiglobal.h"
#include "kopetemetacontact.h"

//liboscar
#include "client.h"
#include "oscartypes.h"
#include "oscarutils.h"
#include "ssimanager.h"

#include "aimprotocol.h"
#include "aimuserinfo.h"
#include "aimcontact.h"
#include "aimaccount.h"

AIMContact::AIMContact( Kopete::Account* account, const TQString& name, Kopete::MetaContact* parent,
                        const TQString& icon, const Oscar::SSI& ssiItem )
: OscarContact(account, name, parent, icon, ssiItem )
{
	mProtocol=static_cast<AIMProtocol *>(protocol());
	setOnlineStatus( mProtocol->statusOffline );

	m_infoDialog = 0L;
	m_warnUserAction = 0L;
	mUserProfile="";
	m_haveAwayMessage = false;
	m_mobile = false;
	// Set the last autoresponse time to the current time yesterday
	m_lastAutoresponseTime = TQDateTime::currentDateTime().addDays(-1);

	TQObject::connect( mAccount->engine(), TQ_SIGNAL( receivedUserInfo( const TQString&, const UserDetails& ) ),
	                  this, TQ_SLOT( userInfoUpdated( const TQString&, const UserDetails& ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( userIsOffline( const TQString& ) ),
	                  this, TQ_SLOT( userOffline( const TQString& ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( receivedAwayMessage( const TQString&, const TQString& ) ),
	                  this, TQ_SLOT( updateAwayMessage( const TQString&, const TQString& ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( receivedProfile( const TQString&, const TQString& ) ),
	                  this, TQ_SLOT( updateProfile( const TQString&, const TQString& ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( userWarned( const TQString&, TQ_UINT16, TQ_UINT16 ) ),
	                  this, TQ_SLOT( gotWarning( const TQString&, TQ_UINT16, TQ_UINT16 ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( haveIconForContact( const TQString&, TQByteArray ) ),
	                  this, TQ_SLOT( haveIcon( const TQString&, TQByteArray ) ) );
	TQObject::connect( mAccount->engine(), TQ_SIGNAL( iconServerConnected() ),
	                  this, TQ_SLOT( requestBuddyIcon() ) );
	TQObject::connect( this, TQ_SIGNAL( featuresUpdated() ), this, TQ_SLOT( updateFeatures() ) );
}

AIMContact::~AIMContact()
{
}

bool AIMContact::isReachable()
{
	return true;
}

TQPtrList<TDEAction> *AIMContact::customContextMenuActions()
{

	TQPtrList<TDEAction> *actionCollection = new TQPtrList<TDEAction>();
	if ( !m_warnUserAction )
	{
		m_warnUserAction = new TDEAction( i18n( "&Warn User" ), 0, this, TQ_SLOT( warnUser() ), this, "warnAction" );
	}
	m_actionVisibleTo = new TDEToggleAction(i18n("Always &Visible To"), "", 0,
	                                      this, TQ_SLOT(slotVisibleTo()), this, "actionVisibleTo");
	m_actionInvisibleTo = new TDEToggleAction(i18n("Always &Invisible To"), "", 0,
	                                        this, TQ_SLOT(slotInvisibleTo()), this, "actionInvisibleTo");
	
	bool on = account()->isConnected();

	m_warnUserAction->setEnabled( on );

	m_actionVisibleTo->setEnabled(on);
	m_actionInvisibleTo->setEnabled(on);

	SSIManager* ssi = account()->engine()->ssiManager();
	m_actionVisibleTo->setChecked( ssi->findItem( m_ssiItem.name(), ROSTER_VISIBLE ));
	m_actionInvisibleTo->setChecked( ssi->findItem( m_ssiItem.name(), ROSTER_INVISIBLE ));

	actionCollection->append( m_warnUserAction );

	actionCollection->append(m_actionVisibleTo);
	actionCollection->append(m_actionInvisibleTo);


	return actionCollection;
}

const TQString AIMContact::awayMessage()
{
	return property(mProtocol->awayMessage).value().toString();
}

void AIMContact::setAwayMessage(const TQString &message)
{
	kdDebug(14152) << k_funcinfo <<
		"Called for '" << contactId() << "', away msg='" << message << "'" << endl;
	TQString filteredMessage = message;
	filteredMessage.replace(
		TQRegExp(TQString::fromLatin1("<[hH][tT][mM][lL].*>(.*)</[hH][tT][mM][lL]>")),
		TQString::fromLatin1("\\1"));
	filteredMessage.replace(
		TQRegExp(TQString::fromLatin1("<[bB][oO][dD][yY].*>(.*)</[bB][oO][dD][yY]>")),
		TQString::fromLatin1("\\1") );
	TQRegExp fontRemover( TQString::fromLatin1("<[fF][oO][nN][tT].*>(.*)</[fF][oO][nN][tT]>") );
	fontRemover.setMinimal(true);
	while ( filteredMessage.find( fontRemover ) != -1 )
		filteredMessage.replace( fontRemover, TQString::fromLatin1("\\1") );
	setProperty(mProtocol->awayMessage, filteredMessage);
}

int AIMContact::warningLevel() const
{
	return m_warningLevel;
}

void AIMContact::updateSSIItem()
{
	if ( m_ssiItem.type() != 0xFFFF && m_ssiItem.waitingAuth() == false &&
	     onlineStatus() == Kopete::OnlineStatus::Unknown )
	{
		//make sure they're offline
		setOnlineStatus( static_cast<AIMProtocol*>( protocol() )->statusOffline );
	}
}

void AIMContact::slotUserInfo()
{
	if ( !m_infoDialog)
	{
		m_infoDialog = new AIMUserInfoDialog( this, static_cast<AIMAccount*>( account() ), false, Kopete::UI::Global::mainWidget(), 0 );
		if( !m_infoDialog )
			return;
		connect( m_infoDialog, TQ_SIGNAL( finished() ), this, TQ_SLOT( closeUserInfoDialog() ) );
		m_infoDialog->show();
		if ( mAccount->isConnected() )
		{
			mAccount->engine()->requestAIMProfile( contactId() );
			mAccount->engine()->requestAIMAwayMessage( contactId() );
		}
	}
	else
		m_infoDialog->raise();
}

void AIMContact::userInfoUpdated( const TQString& contact, const UserDetails& details )
{
	if ( Oscar::normalize( contact ) != Oscar::normalize( contactId() ) )
		return;

	kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << contact << endl;

	//if they don't have an SSI alias, make sure we use the capitalization from the
	//server so their contact id looks all pretty.
	TQString nickname = property( Kopete::Global::Properties::self()->nickName() ).value().toString();
	if ( nickname.isEmpty() || Oscar::normalize( nickname ) == Oscar::normalize( contact ) )
		setNickName( contact );

	( details.userClass() & CLASS_WIRELESS ) ? m_mobile = true : m_mobile = false;

	if ( ( details.userClass() & CLASS_AWAY ) == STATUS_ONLINE )
	{
		if ( m_mobile ) 
		{
			kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Contact: " << contact << " is mobile-online." << endl;
			setOnlineStatus( mProtocol->statusWirelessOnline );
    	}
		else 
		{
			kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Contact: " << contact << " is online." << endl;
			setOnlineStatus( mProtocol->statusOnline ); //we're online
		}
		removeProperty( mProtocol->awayMessage );
		m_haveAwayMessage = false;
	}
	else if ( ( details.userClass() & CLASS_AWAY ) ) // STATUS_AWAY
	{
		if ( m_mobile ) 
		{
			kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Contact: " << contact << " is mobile-away." << endl;
			setOnlineStatus( mProtocol->statusWirelessOnline );
		}
		else 
		{
			kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Contact: " << contact << " is away." << endl;
			setOnlineStatus( mProtocol->statusAway ); //we're away
		}
		if ( !m_haveAwayMessage ) //prevent cyclic away message requests
		{
			mAccount->engine()->requestAIMAwayMessage( contactId() );
			m_haveAwayMessage = true;
		}
	}
	else
	{
        kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Contact: " << contact << " class " << details.userClass() << " is unhandled... defaulting to away." << endl;
		setOnlineStatus( mProtocol->statusAway ); //we're away
		if ( !m_haveAwayMessage ) //prevent cyclic away message requests
		{
			mAccount->engine()->requestAIMAwayMessage( contactId() );
			m_haveAwayMessage = true;
		}
	}

	if ( details.buddyIconHash().size() > 0 && details.buddyIconHash() != m_details.buddyIconHash() )
	{
        if ( !mAccount->engine()->hasIconConnection() )
            mAccount->engine()->requestServerRedirect( 0x0010 );

		int time = ( TDEApplication::random() % 10 ) * 1000;
		kdDebug(OSCAR_ICQ_DEBUG) << k_funcinfo << "updating buddy icon in " << time/1000 << " seconds" << endl;
		TQTimer::singleShot( time, this, TQ_SLOT( requestBuddyIcon() ) );
	}

	OscarContact::userInfoUpdated( contact, details );
}

void AIMContact::userOnline( const TQString& userId )
{
	if ( Oscar::normalize( userId ) == Oscar::normalize( contactId() ) )
	{
		kdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "Getting more contact info" << endl;
		setOnlineStatus( mProtocol->statusOnline );
	}
}

void AIMContact::userOffline( const TQString& userId )
{
	if ( Oscar::normalize( userId ) == Oscar::normalize( contactId() ) )
	{
		setOnlineStatus( mProtocol->statusOffline );
		removeProperty( mProtocol->awayMessage );
	}
}

void AIMContact::updateAwayMessage( const TQString& contact, const TQString& message )
{
	if ( Oscar::normalize( contact ) != Oscar::normalize( contactId() ) )
		return;
	else
	{
		if ( message.isEmpty() )
		{
			removeProperty( mProtocol->awayMessage );
			if ( !m_mobile )
				setOnlineStatus( mProtocol->statusOnline );
			else
				setOnlineStatus( mProtocol->statusWirelessOnline );
			m_haveAwayMessage = false;
		}
		else
		{
			m_haveAwayMessage = true;
			setAwayMessage( message );
			if ( !m_mobile )
				setOnlineStatus( mProtocol->statusAway );
			else
				setOnlineStatus( mProtocol->statusWirelessAway );
		}
	}

	emit updatedProfile();
}

void AIMContact::updateProfile( const TQString& contact, const TQString& profile )
{
	if ( Oscar::normalize( contact ) != Oscar::normalize( contactId() ) )
		return;

	setProperty( mProtocol->clientProfile, profile );
	emit updatedProfile();
}

void AIMContact::gotWarning( const TQString& contact, TQ_UINT16 increase, TQ_UINT16 newLevel )
{
	//somebody just got bitchslapped! :O
	Q_UNUSED( increase );
	if ( Oscar::normalize( contact ) == Oscar::normalize( contactId() ) )
		m_warningLevel = newLevel;

	//TODO add a KNotify event after merge to HEAD
}

void AIMContact::requestBuddyIcon()
{
	kdDebug(OSCAR_AIM_DEBUG) << k_funcinfo << "Updating buddy icon for " << contactId() << endl;
	if ( m_details.buddyIconHash().size() > 0 )
	{
		account()->engine()->requestBuddyIcon( contactId(), m_details.buddyIconHash(),
		                                       m_details.iconCheckSumType() );
	}
}

void AIMContact::haveIcon( const TQString& user, TQByteArray icon )
{
	if ( Oscar::normalize( user ) != Oscar::normalize( contactId() ) )
		return;

	kdDebug(OSCAR_AIM_DEBUG) << k_funcinfo << "Updating icon for " << contactId() << endl;
	TQImage buddyIcon( icon );
	if ( buddyIcon.isNull() )
	{
		kdWarning(OSCAR_AIM_DEBUG) << k_funcinfo << "Failed to convert buddy icon to TQImage" << endl;
		return;
	}

	setProperty( Kopete::Global::Properties::self()->photo(), buddyIcon );
}

void AIMContact::closeUserInfoDialog()
{
	m_infoDialog->delayedDestruct();
	m_infoDialog = 0L;
}

void AIMContact::warnUser()
{
	TQString nick = property( Kopete::Global::Properties::self()->nickName() ).value().toString();
	TQString message = i18n( "<qt>Would you like to warn %1 anonymously or with your name?<br>" \
	                        "(Warning a user on AIM will result in a \"Warning Level\"" \
	                        " increasing for the user you warn. Once this level has reached a" \
	                        " certain point, they will not be able to sign on. Please do not abuse" \
	                        " this function, it is meant for legitimate practices.)</qt>" ).arg( nick );


	int result = KMessageBox::questionYesNoCancel( Kopete::UI::Global::mainWidget(), message,
	                                               i18n( "Warn User %1?" ).arg( nick ),
	                                               i18n( "Warn Anonymously" ), i18n( "Warn" ) );

	if ( result == KMessageBox::Yes )
		mAccount->engine()->sendWarning( contactId(), true);
	else if ( result == KMessageBox::No )
		mAccount->engine()->sendWarning( contactId(), false);
}

void AIMContact::slotVisibleTo()
{
	account()->engine()->setVisibleTo( contactId(), m_actionVisibleTo->isChecked() );
}

void AIMContact::slotInvisibleTo()
{
	account()->engine()->setInvisibleTo( contactId(), m_actionInvisibleTo->isChecked() );
}

void AIMContact::slotSendMsg(Kopete::Message& message, Kopete::ChatSession *)
{
	Oscar::Message msg;
	TQString s;

	if (message.plainBody().isEmpty()) // no text, do nothing
		return;
	//okay, now we need to change the message.escapedBody from real HTML to aimhtml.
	//looking right now for docs on that "format".
	//looks like everything except for alignment codes comes in the format of spans

	//font-style:italic -> <i>
	//font-weight:600 -> <b> (anything > 400 should be <b>, 400 is not bold)
	//text-decoration:underline -> <u>
	//font-family: -> <font face="">
	//font-size:xxpt -> <font ptsize=xx>

	s=message.escapedBody();
	s.replace ( TQRegExp( TQString::fromLatin1("<span style=\"([^\"]*)\">([^<]*)</span>")),
			TQString::fromLatin1("<style>\\1;\"\\2</style>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)font-style:italic;([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("<i><style>\\1\\2\"\\3</style></i>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)font-weight:600;([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("<b><style>\\1\\2\"\\3</style></b>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)text-decoration:underline;([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("<u><style>\\1\\2\"\\3</style></u>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)font-family:([^;]*);([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("<font face=\"\\2\"><style>\\1\\3\"\\4</style></font>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)font-size:([^p]*)pt;([^\"]*)\"([^<]*)</style>")),
				TQString::fromLatin1("<font ptsize=\"\\2\"><style>\\1\\3\"\\4</style></font>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)color:([^;]*);([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("<font color=\"\\2\"><style>\\1\\3\"\\4</style></font>"));

	s.replace ( TQRegExp( TQString::fromLatin1("<style>([^\"]*)\"([^<]*)</style>")),
	            TQString::fromLatin1("\\2"));

	//okay now change the <font ptsize="xx"> to <font size="xx">

	//0-9 are size 1
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"\\d\">")),
	            TQString::fromLatin1("<font size=\"1\">"));
	//10-11 are size 2
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"1[01]\">")),
	            TQString::fromLatin1("<font size=\"2\">"));
	//12-13 are size 3
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"1[23]\">")),
	            TQString::fromLatin1("<font size=\"3\">"));
	//14-16 are size 4
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"1[456]\">")),
	            TQString::fromLatin1("<font size=\"4\">"));
	//17-22 are size 5
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"(?:1[789]|2[012])\">")),
	            TQString::fromLatin1("<font size=\"5\">"));
	//23-29 are size 6
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"2[3456789]\">")),TQString::fromLatin1("<font size=\"6\">"));
	//30- (and any I missed) are size 7
	s.replace ( TQRegExp ( TQString::fromLatin1("<font ptsize=\"[^\"]*\">")),TQString::fromLatin1("<font size=\"7\">"));

	// strip left over line break
	s.remove(TQRegExp(TQString::fromLatin1("<br\b[^>]*>$")));

	s.replace ( TQRegExp ( TQString::fromLatin1("<br[ /]*>")), TQString::fromLatin1("<br>") );

	// strip left over line break
	s.remove( TQRegExp( TQString::fromLatin1( "<br>$" ) ) );

	kdDebug(14190) << k_funcinfo << "sending "
		<< s << endl;

	// XXX Need to check for message size?

	if ( m_details.hasCap( CAP_UTF8 ) )
		msg.setText( Oscar::Message::UCS2, s );
	else
		msg.setText( Oscar::Message::UserDefined, s, contactCodec() );

	msg.setReceiver(mName);
	msg.setTimestamp(message.timestamp());
	msg.setType(0x01);

	mAccount->engine()->sendMessage(msg);

	// Show the message we just sent in the chat window
	manager(Kopete::Contact::CanCreate)->appendMessage(message);
	manager(Kopete::Contact::CanCreate)->messageSucceeded();
}

void AIMContact::updateFeatures()
{
	setProperty( static_cast<AIMProtocol*>(protocol())->clientFeatures, m_clientFeatures );
}

void AIMContact::sendAutoResponse(Kopete::Message& msg)
{
	// The target time is 2 minutes later than the last message
	int delta = m_lastAutoresponseTime.secsTo( TQDateTime::currentDateTime() );
	kdDebug(14152) << k_funcinfo << "Last autoresponse time: " << m_lastAutoresponseTime << endl;
	kdDebug(14152) << k_funcinfo << "Current time: " << TQDateTime::currentDateTime() << endl;
	kdDebug(14152) << k_funcinfo << "Difference: " << delta << endl;
	// Check to see if we're past that time
	if(delta > 120)
	{
		kdDebug(14152) << k_funcinfo << "Sending auto response" << endl;

		// This code was yoinked straight from OscarContact::slotSendMsg()
		// If only that slot wasn't private, but I'm not gonna change it right now.
		Oscar::Message message;

		if ( m_details.hasCap( CAP_UTF8 ) )
		{
			message.setText( Oscar::Message::UCS2, msg.plainBody() );
		}
		else
		{
			TQTextCodec* codec = contactCodec();
			message.setText( Oscar::Message::UserDefined, msg.plainBody(), codec );
		}

		message.setTimestamp( msg.timestamp() );
		message.setSender( mAccount->accountId() );
		message.setReceiver( mName );
		message.setType( 0x01 );

		// isAuto defaults to false
		mAccount->engine()->sendMessage( message, true);
		kdDebug(14152) << k_funcinfo << "Sent auto response" << endl;
		manager(Kopete::Contact::CanCreate)->appendMessage(msg);
		manager(Kopete::Contact::CanCreate)->messageSucceeded();
		// Update the last autoresponse time
		m_lastAutoresponseTime = TQDateTime::currentDateTime();
	}
	else
	{
		kdDebug(14152) << k_funcinfo << "Not enough time since last autoresponse, NOT sending" << endl;
	}
}
#include "aimcontact.moc"