summaryrefslogtreecommitdiffstats
path: root/kopete/protocols/yahoo/libkyahoo/webcamtask.cpp
blob: addcb15ab306672dc37723902ba727092ad70c10 (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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/*
    Kopete Yahoo Protocol
    Handles incoming webcam connections

    Copyright (c) 2005 André Duffeck <duffeck@kde.org>

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

#include "webcamtask.h"
#include "sendnotifytask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"

#include <tqbuffer.h>
#include <tqfile.h>
#include <tqtimer.h>
#include <tqpixmap.h>
#include <ktempfile.h>
#include <kprocess.h>
#include <kstreamsocket.h>
#include <kdebug.h>
#include <klocale.h>

using namespace KNetwork;

WebcamTask::WebcamTask(Task* parent) : Task(parent)
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	transmittingData = false;
	transmissionPending = false;
	timestamp = 1;
}

WebcamTask::~WebcamTask()
{
}

bool WebcamTask::take( Transfer* transfer )
{
	if ( !forMe( transfer ) )
		return false;

	YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);

 	if( t->service() == Yahoo::ServiceWebcam )
 		parseWebcamInformation( t );
// 	else
// 		parseMessage( transfer );

	return true;
}

bool WebcamTask::forMe( const Transfer* transfer ) const
{
	const YMSGTransfer *t = 0L;
	t = dynamic_cast<const YMSGTransfer*>(transfer);
	if (!t)
		return false;

	if ( t->service() == Yahoo::ServiceWebcam )
		return true;
	else
		return false;
}

void WebcamTask::requestWebcam( const TQString &who )
{
	kdDebug(YAHOO_RAW_DEBUG) ;

	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceWebcam);
	t->setId( client()->sessionID() );
	t->setParam( 1, client()->userId().local8Bit());
	t->setParam( 5, who.local8Bit() );
	keyPending = who;

	send( t );
}

void WebcamTask::parseWebcamInformation( YMSGTransfer *t )
{
	kdDebug(YAHOO_RAW_DEBUG) ;

	YahooWebcamInformation info;
	info.sender = keyPending;
	info.server = t->firstParam( 102 );
	info.key = t->firstParam( 61 );
	info.status = InitialStatus;
	info.dataLength = 0;
	info.buffer = 0L;
	info.headerRead = false;
	if( info.sender == client()->userId() )
	{
		transmittingData = true;
		info.direction = Outgoing;
	}
	else
		info.direction = Incoming;

	kdDebug(YAHOO_RAW_DEBUG) << "Got WebcamInformation: Sender: " << info.sender << " Server: " << info.server << " Key: " << info.key << endl;

	KStreamSocket *socket = new KStreamSocket( info.server, TQString::number(5100) );
	socketMap[socket] = info;
	socket->enableRead( true );
	connect( socket, TQT_SIGNAL( connected( const KResolverEntry& ) ), this, TQT_SLOT( slotConnectionStage1Established() ) );
	connect( socket, TQT_SIGNAL( gotError(int) ), this, TQT_SLOT( slotConnectionFailed(int) ) );
	connect( socket, TQT_SIGNAL( readyRead() ), this, TQT_SLOT( slotRead() ) );

	socket->connect();
}

void WebcamTask::slotConnectionStage1Established()
{
	KStreamSocket* socket = const_cast<KStreamSocket*>( dynamic_cast<const KStreamSocket*>( sender() ) );
	if( !socket )
		return;
	kdDebug(YAHOO_RAW_DEBUG) << "Webcam connection Stage1 to the user " << socketMap[socket].sender << " established." << endl;
	disconnect( socket, TQT_SIGNAL( connected( const KResolverEntry& ) ), this, TQT_SLOT( slotConnectionStage1Established() ) );
	disconnect( socket, TQT_SIGNAL( gotError(int) ), this, TQT_SLOT( slotConnectionFailed(int) ) );
	socketMap[socket].status = ConnectedStage1;


	TQByteArray buffer;
	TQDataStream stream( buffer, IO_WriteOnly );
	TQString s;
	if( socketMap[socket].direction == Incoming )
	{
		socket->writeBlock( TQCString("<RVWCFG>").data(), 8 );
		s = TQString("g=%1\r\n").tqarg(socketMap[socket].sender);
	}
	else
	{
		socket->writeBlock( TQCString("<RUPCFG>").data(), 8 );
		s = TQString("f=1\r\n");
	}

	// Header: 08 00 01 00 00 00 00
	stream << (TQ_INT8)0x08 << (TQ_INT8)0x00 << (TQ_INT8)0x01 << (TQ_INT8)0x00 << (TQ_INT32)s.length();
	stream.writeRawBytes( s.local8Bit(), s.length() );

	socket->writeBlock( buffer.data(), buffer.size() );
}

void WebcamTask::slotConnectionStage2Established()
{
	KStreamSocket* socket = const_cast<KStreamSocket*>( dynamic_cast<const KStreamSocket*>( sender() ) );
	if( !socket )
		return;

	kdDebug(YAHOO_RAW_DEBUG) << "Webcam connection Stage2 to the user " << socketMap[socket].sender << " established." << endl;
	disconnect( socket, TQT_SIGNAL( connected( const KResolverEntry& ) ), this, TQT_SLOT( slotConnectionStage2Established() ) );
	disconnect( socket, TQT_SIGNAL( gotError(int) ), this, TQT_SLOT( slotConnectionFailed(int) ) );
	socketMap[socket].status = ConnectedStage2;

	TQByteArray buffer;
	TQDataStream stream( buffer, IO_WriteOnly );
	TQString s;


	if( socketMap[socket].direction == Incoming )
	{
		// Send <RETQIMG>-Packet
		socket->writeBlock( TQCString("<RETQIMG>").data(), 8 );
		// Send request information
		s = TQString("a=2\r\nc=us\r\ne=21\r\nu=%1\r\nt=%2\r\ni=\r\ng=%3\r\no=w-2-5-1\r\np=1")
			.tqarg(client()->userId()).tqarg(socketMap[socket].key).tqarg(socketMap[socket].sender);
		// Header: 08 00 01 00 00 00 00
		stream << (TQ_INT8)0x08 << (TQ_INT8)0x00 << (TQ_INT8)0x01 << (TQ_INT8)0x00 << (TQ_INT32)s.length();
	}
	else
	{
		// Send <RETQIMG>-Packet
		socket->writeBlock( TQCString("<SNDIMG>").data(), 8 );
		// Send request information
		s = TQString("a=2\r\nc=us\r\nu=%1\r\nt=%2\r\ni=%3\r\no=w-2-5-1\r\np=2\r\nb=KopeteWebcam\r\nd=\r\n")
		.tqarg(client()->userId()).tqarg(socketMap[socket].key).tqarg(socket->localAddress().nodeName());
		// Header: 08 00 05 00 00 00 00	01 00 00 00 01
		stream << (TQ_INT8)0x0d << (TQ_INT8)0x00 << (TQ_INT8)0x05 << (TQ_INT8)0x00 << (TQ_INT32)s.length()
			<< (TQ_INT8)0x01 << (TQ_INT8)0x00 << (TQ_INT8)0x00 << (TQ_INT8)0x00 << (TQ_INT8)0x01;
	}

	socket->writeBlock( buffer.data(), buffer.size() );
        socket->writeBlock( s.local8Bit(), s.length() );
}

void WebcamTask::slotConnectionFailed( int error )
{
	KStreamSocket* socket = const_cast<KStreamSocket*>( dynamic_cast<const KStreamSocket*>( sender() ) );
	kdDebug(YAHOO_RAW_DEBUG) << "Webcam connection to the user " << socketMap[socket].sender << " failed. Error " << error << " - " << socket->KSocketBase::errorString() << endl;
        client()->notifyError( i18n("Webcam connection to the user %1 could not be established.\n\nPlease relogin and try again.")
                        .tqarg(socketMap[socket].sender), TQString("%1 - %2").tqarg(error).tqarg( socket->KSocketBase::errorString()), Client::Error );
        socketMap.remove( socket );
        socket->deleteLater();
}

void WebcamTask::slotRead()
{
	KStreamSocket* socket = const_cast<KStreamSocket*>( dynamic_cast<const KStreamSocket*>( sender() ) );
	if( !socket )
		return;

	switch( socketMap[socket].status )
	{
		case ConnectedStage1:
			disconnect( socket, TQT_SIGNAL( readyRead() ), this, TQT_SLOT( slotRead() ) );
			connectStage2( socket );
		break;
		case ConnectedStage2:
		case Sending:
		case SendingEmpty:
			processData( socket );
		default:
		break;
	}
}

void WebcamTask::connectStage2( KStreamSocket *socket )
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	TQByteArray data( socket->bytesAvailable() );
	socket->readBlock ( data.data (), data.size () );
	kdDebug(YAHOO_RAW_DEBUG) << "Magic Byte:" << data[2] << endl;

	socketMap[socket].status = ConnectedStage2;

	TQString server;
	int i = 4;
	KStreamSocket *newSocket;
	switch( (const char)data[2] )
	{
	case (TQ_INT8)0x06:
		emit webcamNotAvailable(socketMap[socket].sender);
		break;
	case (TQ_INT8)0x04:
	case (TQ_INT8)0x07:
		while( (const char)data[i] != (TQ_INT8)0x00 )
			server += data[i++];
		kdDebug(YAHOO_RAW_DEBUG) << "Server:" << server << endl;
		if( server.isEmpty() )
		{
			emit webcamNotAvailable(socketMap[socket].sender);
			break;
		}

		kdDebug(YAHOO_RAW_DEBUG) << "Connecting to " << server << endl;
		newSocket = new KStreamSocket( server, TQString::number(5100) );
		socketMap[newSocket] = socketMap[socket];
		newSocket->enableRead( true );
		connect( newSocket, TQT_SIGNAL( connected( const KResolverEntry& ) ), this, TQT_SLOT( slotConnectionStage2Established() ) );
		connect( newSocket, TQT_SIGNAL( gotError(int) ), this, TQT_SLOT( slotConnectionFailed(int) ) );
		connect( newSocket, TQT_SIGNAL( readyRead() ), this, TQT_SLOT( slotRead() ) );
		if( socketMap[newSocket].direction == Outgoing )
		{
			newSocket->enableWrite( true );
			connect( newSocket, TQT_SIGNAL( readyWrite() ), this, TQT_SLOT( transmitWebcamImage() ) );
		}

		newSocket->connect();
		break;
	default:
		break;
	}
	socketMap.remove( socket );
	delete socket;
}

void WebcamTask::processData( KStreamSocket *socket )
{
	TQByteArray data( socket->bytesAvailable() );

	socket->readBlock ( data.data (), data.size () );

	if( data.size() <= 0 )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "No data read." << endl;
		return;
	}

	parseData( data, socket );
}

void WebcamTask::parseData( TQByteArray &data, KStreamSocket *socket )
{
	int headerLength = 0;
	int read = 0;
	YahooWebcamInformation *info = &socketMap[socket];
	if( !info->headerRead )
	{
		headerLength = data[0];
		kdDebug(YAHOO_RAW_DEBUG) << "headerLength " << headerLength << endl;
		if( data.size() < headerLength )
			return;
		if( headerLength >= 8 )
		{
			kdDebug() << data[0] << data[1] << data[2] << data[3] << data[4] << data[5] << data[6] << data[7] << endl;
			info->reason = data[1];
			info->dataLength = yahoo_get32(data.data() + 4);
		}
		if( headerLength == 13 )
		{
			kdDebug() << data[8] << data[9] << data[10] << data[11] << data[12] << endl;
			info->timestamp = yahoo_get32(data.data() + 9);
			kdDebug(YAHOO_RAW_DEBUG) << "PacketType: " << data[8] << " reason: " << info->reason << " timestamp: " << info->timestamp << endl;
			TQStringList::iterator it;
			switch( data[8] )
			{
				case 0x00:
					if( info->direction == Incoming )
					{
						if( info->timestamp == 0 )
						{
							emit webcamClosed( info->sender, 3 );
							cleanUpConnection( socket );
						}
					}
					else
					{
						info->type = UserRequest;
						info->headerRead = true;
					}
				break;
				case 0x02:
					info->type = Image;
					info->headerRead = true;
				break;
				case 0x04:
					if( info->timestamp == 1 )
					{
						emit webcamPaused( info->sender );
					}
				break;
				case 0x05:
					kdDebug(YAHOO_RAW_DEBUG) << "Ready for Transmission" << endl;
					if( info->timestamp == 1 )
					{
						info->status = Sending;
						emit readyForTransmission();
					}
					else if( info->timestamp == 0 )
					{
						info->status = SendingEmpty;
						emit stopTransmission();
						sendEmptyWebcamImage();
					}

					// Send Invitation packets
					for(it = pendingInvitations.begin(); it != pendingInvitations.end(); it++)
					{
						SendNotifyTask *snt = new SendNotifyTask( parent() );
						snt->setTarget( *it );
						snt->setType( SendNotifyTask::NotifyWebcamInvite );
						snt->go( true );
						it = pendingInvitations.erase( it );
						it--;
					}
				break;
				case 0x07:

					info->type = ConnectionClosed;
					emit webcamClosed( info->sender, info->reason );
					cleanUpConnection( socket );
				case 0x0c:
					info->type = NewWatcher;
					info->headerRead = true;
				break;
				case 0x0d:
					info->type = WatcherLeft;
					info->headerRead = true;
				break;
			}
		}
		if( headerLength > 13 || headerLength <= 0)		//Parse error
			return;
		if( !info->headerRead && data.size() > headerLength )
		{
			// More headers to read
			kdDebug(YAHOO_RAW_DEBUG) << "More data to read..." << endl;
			TQByteArray newData( data.size() - headerLength );
			TQDataStream stream( newData, IO_WriteOnly );
			stream.writeRawBytes( data.data() + headerLength, data.size() - headerLength );
			parseData( newData, socket );
			return;
		}
		kdDebug(YAHOO_RAW_DEBUG) << "Parsed Packet: HeaderLen: " << headerLength << " DataLen: " << info->dataLength << endl;
	}

	if( info->dataLength <= 0 )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "No data to read. (info->dataLength <= 0)" << endl;
		if( info->headerRead )
			info->headerRead = false;
		return;
	}
	if( headerLength >= data.size() )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "No data to read. (headerLength >= data.size())" << endl;
		return;		//Nothing to read here...
	}
	if( !info->buffer )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Buffer created" << endl;
		info->buffer = new TQBuffer();
		info->buffer->open( IO_WriteOnly );
	}

	kdDebug(YAHOO_RAW_DEBUG) << "data.size() " << data.size() << " headerLength " << headerLength << " buffersize " << info->buffer->size() << endl;
	read = headerLength + info->dataLength - info->buffer->size();
	info->buffer->writeBlock( data.data() + headerLength, data.size() - headerLength );//info->dataLength - info->buffer->size() );
	kdDebug(YAHOO_RAW_DEBUG) << "read " << data.size() - headerLength << " Bytes, Buffer is now " << info->buffer->size() << endl;
	if( info->buffer->size() >= static_cast<uint>(info->dataLength) )
	{
		info->buffer->close();
		TQString who;
		switch( info->type )
		{
		case UserRequest:
			{
			who.append( info->buffer->buffer() );
			who = who.mid( 2, who.find('\n') - 3);
			kdDebug(YAHOO_RAW_DEBUG) << "User wants to view webcam: " << who << " len: " << who.length() << " Index: " << accessGranted.findIndex( who ) << endl;
			if( accessGranted.findIndex( who ) >= 0 )
			{
				grantAccess( who );
			}
			else
				emit viewerRequest( who );
			}
		break;
		case NewWatcher:
			who.append( info->buffer->buffer() );
			who = who.left( who.length() - 1 );
			kdDebug(YAHOO_RAW_DEBUG) << "New Watcher of webcam: " << who << endl;
			emit viewerJoined( who );
		break;
		case WatcherLeft:
			who.append( info->buffer->buffer() );
			who = who.left( who.length() - 1 );
			kdDebug(YAHOO_RAW_DEBUG) << "A Watcher left: " << who << " len: " << who.length() << endl;
			accessGranted.remove( who );
			emit viewerLeft( who );
		break;
		case Image:
			{
			TQPixmap webcamImage;
			//webcamImage.loadFromData( info->buffer->buffer() );

			// FIXME (same)
			//KTemporaryFile jpcTmpImageFile;
			//jpcTmpImageFile.setAutoRemove(false);
			//jpcTmpImageFile.open();
			//KTemporaryFile bmpTmpImageFile;
			//bmpTmpImageFile.setAutoRemove(false);
			//bmpTmpImageFile.open();

			//jpcTmpImageFile.write((info->buffer->buffer()).data(), info->buffer->size());
			//jpcTmpImageFile.close();

			KTempFile jpcTmpImageFile;
                        KTempFile bmpTmpImageFile;
                        TQFile *file = jpcTmpImageFile.file();
                        file->writeBlock((info->buffer->buffer()).data(), info->buffer->size());
                        file->close();

			KProcess p;
			p << "jasper";
			p << "--input" << jpcTmpImageFile.name() << "--output" << bmpTmpImageFile.name() << "--output-format" << "bmp";

			p.start( KProcess::Block );
			if( p.exitStatus() != 0 )
			{
				kdDebug(YAHOO_RAW_DEBUG) << " jasper exited with status " << p.exitStatus() << " " << info->sender << endl;
			}
			else
			{
				webcamImage.load( bmpTmpImageFile.name() );
				/******* UPTO THIS POINT ******/
				emit webcamImageReceived( info->sender, webcamImage );
			}
			TQFile::remove(jpcTmpImageFile.name());
                        TQFile::remove(bmpTmpImageFile.name());

			kdDebug(YAHOO_RAW_DEBUG) << "Image Received. Size: " << webcamImage.size() << endl;
			}
		break;
		default:
		break;
		}

		info->headerRead = false;
		delete info->buffer;
		info->buffer = 0L;
	}
	if( data.size() > read )
	{
		// More headers to read
		kdDebug(YAHOO_RAW_DEBUG) << "More data to read..." << data.size() - read << endl;
		TQByteArray newData( data.size() - read );
		TQDataStream stream( newData, IO_WriteOnly );
		stream.writeRawBytes( data.data() + read, data.size() - read );
		parseData( newData, socket );
	}
}

void WebcamTask::cleanUpConnection( KStreamSocket *socket )
{
	socket->close();
	YahooWebcamInformation *info = &socketMap[socket];
	if( info->buffer )
		delete info->buffer;
	socketMap.remove( socket );
	delete socket;
}

void WebcamTask::closeWebcam( const TQString & who )
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		kdDebug(YAHOO_RAW_DEBUG) << it.data().sender << " - " << who << endl;
		if( it.data().sender == who )
		{
			cleanUpConnection( it.key() );
			return;
		}
	}
	kdDebug(YAHOO_RAW_DEBUG) << "Error. You tried to close a connection that did not exist." << endl;
	client()->notifyError( i18n( "An error occurred closing the webcam session. " ), i18n( "You tried to close a connection that did not exist." ), Client::Debug );
}


// Sending

void WebcamTask::registerWebcam()
{
	kdDebug(YAHOO_RAW_DEBUG) ;

	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceWebcam);
	t->setId( client()->sessionID() );
	t->setParam( 1, client()->userId().local8Bit());
	keyPending  = client()->userId();

	send( t );
}

void WebcamTask::addPendingInvitation( const TQString &userId )
{
	kdDebug(YAHOO_RAW_DEBUG) << "Inviting " << userId << " to watch the webcam." << endl;
	pendingInvitations.append( userId );
	accessGranted.append( userId );
}

void WebcamTask::grantAccess( const TQString &userId )
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	KStreamSocket *socket = 0L;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		if( it.data().direction == Outgoing )
		{
			socket = it.key();
			break;
		}
	}
	if( !socket )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Error. No outgoing socket found." << endl;
		return;
	}
	TQByteArray ar;
	TQDataStream stream( ar, IO_WriteOnly );
	TQString user = TQString("u=%1").tqarg(userId);

	stream << (TQ_INT8)0x0d << (TQ_INT8)0x00 << (TQ_INT8)0x05 << (TQ_INT8)0x00 << (TQ_INT32)user.length()
	<< (TQ_INT8)0x00 << (TQ_INT8)0x00 << (TQ_INT8)0x00 << (TQ_INT8)0x00 << (TQ_INT8)0x01;
	socket->writeBlock( ar.data(), ar.size() );
        socket->writeBlock( user.local8Bit(), user.length() );
}

void WebcamTask::closeOutgoingWebcam()
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	KStreamSocket *socket = 0L;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		if( it.data().direction == Outgoing )
		{
			socket = it.key();
			break;
		}
	}
	if( !socket )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Error. No outgoing socket found." << endl;
		return;
	}

	cleanUpConnection( socket );
	transmittingData = false;
}

void WebcamTask::sendEmptyWebcamImage()
{
	kdDebug(YAHOO_RAW_DEBUG) ;

	KStreamSocket *socket = 0L;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		if( it.data().direction == Outgoing )
		{
			socket = it.key();
			break;
		}
	}
	if( !socket )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Error. No outgoing socket found." << endl;
		return;
	}
	if( socketMap[socket].status != SendingEmpty )
		return;

	pictureBuffer.resize( 0 );
	transmissionPending = true;

	TQTimer::singleShot( 1000, this, TQT_SLOT(sendEmptyWebcamImage()) );

}

void WebcamTask::sendWebcamImage( const TQByteArray &image )
{
	kdDebug(YAHOO_RAW_DEBUG) ;
	pictureBuffer = image;
	transmissionPending = true;
	KStreamSocket *socket = 0L;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		if( it.data().direction == Outgoing )
		{
			socket = it.key();
			break;
		}
	}
	if( !socket )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Error. No outgoing socket found." << endl;
		return;
	}

	socket->enableWrite( true );
}

void WebcamTask::transmitWebcamImage()
{
	if( !transmissionPending )
		return;
	kdDebug(YAHOO_RAW_DEBUG) << "arraysize: " << pictureBuffer.size() << endl;

	// Find outgoing socket
	KStreamSocket *socket = 0L;
	SocketInfoMap::Iterator it;
	for( it = socketMap.begin(); it != socketMap.end(); it++ )
	{
		if( it.data().direction == Outgoing )
		{
			socket = it.key();
			break;
		}
	}
	if( !socket )
	{
		kdDebug(YAHOO_RAW_DEBUG) << "Error. No outgoing socket found." << endl;
		return;
	}

	socket->enableWrite( false );
	TQByteArray buffer;
	TQDataStream stream( buffer, IO_WriteOnly );
	stream << (TQ_INT8)0x0d << (TQ_INT8)0x00 << (TQ_INT8)0x05 << (TQ_INT8)0x00 << (TQ_INT32)pictureBuffer.size()
			<< (TQ_INT8)0x02 << (TQ_INT32)timestamp++;
	socket->writeBlock( buffer.data(), buffer.size() );
	if( pictureBuffer.size() )
		socket->writeBlock( pictureBuffer.data(), pictureBuffer.size() );

	transmissionPending = false;
}
#include "webcamtask.moc"