summaryrefslogtreecommitdiffstats
path: root/kipi-plugins/picasawebexport/picasawebtalker.cpp
blob: 693b81e05d2f87431a9fd428208983417ed74c27 (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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/* ============================================================
 *
 * This file is a part of kipi-plugins project
 * http://www.kipi-plugins.org
 *
 * Date        : 2007-16-07
 * Description : a kipi plugin to export images to Picasa web service
 *
 * Copyright (C) 2007-2008 by Vardhman Jain <vardhman at gmail dot com>
 * Copyright (C) 2008 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * 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, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * ============================================================ */

// C++ includes.

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <string>

// Qt includes.

#include <qcstring.h>
#include <qtextstream.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qimage.h>
#include <qstringlist.h>
#include <qurl.h>
#include <qlineedit.h>
#include <qmessagebox.h>
#include <qdom.h>

// KDE includes.

#include <klocale.h>
#include <kio/job.h>
#include <kdebug.h>
#include <kmimetype.h>
#include <kstandarddirs.h>
#include <kmdcodec.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kio/jobclasses.h>
#include <kurl.h>

// LibKExiv2 includes.

#include <libkexiv2/kexiv2.h>

// LibKDcraw includes.

#include <libkdcraw/version.h>
#include <libkdcraw/kdcraw.h>

#if KDCRAW_VERSION < 0x000106
#include <libkdcraw/dcrawbinary.h>
#endif

// Local includes.

#include "pluginsversion.h"
#include "mpform.h"
#include "picasawebitem.h"
#include "picasawebtalker.h"
#include "picasawebwindow.h"
#include "picasaweblogin.h"
#include "picasawebtalker.moc"

class PicasawebLogin;

namespace KIPIPicasawebExportPlugin
{

PicasawebTalker::PicasawebTalker( QWidget* parent )
               : m_parent( parent ),  m_job( 0 )
    {
        m_apikey="49d585bafa0758cb5c58ab67198bf632";
        m_secret="34b39925e6273ffd";

        connect(this, SIGNAL(signalError(const QString&)),
                this, SLOT(slotError(const QString&)));

        authProgressDlg=new QProgressDialog();
    }

PicasawebTalker::~PicasawebTalker()
{
    if (m_job)
        m_job->kill();
}

QString PicasawebTalker::getApiSig(QString secret, QStringList headers)
{
    QStringList compressed ;//= new List<string>(headers.Length);

    for ( QStringList::Iterator it = headers.begin(); it != headers.end(); ++it ) {
        QStringList str=QStringList::split("=",(*it));
        compressed.append(str[0].stripWhiteSpace()+str[1].stripWhiteSpace());
    }

    compressed.sort();
    QString merged=compressed.join("");
    QString final = secret + merged;
    const char *test=final.ascii();
    KMD5 context (test);
    //kdDebug()<< "Test Hex Digest output: " << context.hexDigest().data() << endl;
    return context.hexDigest().data();
}

void PicasawebTalker::getToken(const QString& username, const QString& password )
{
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    QString url = "https://www.google.com/accounts/ClientLogin";

    PicasawebLogin *loginDialog = new PicasawebLogin(kapp->activeWindow(), QString("LoginWindow"), username, password);
    /*if (username!=NULL && username.length() > 0){
        //  kdDebug()<<"Showing stored username"<< username << endl;
        loginDialog->setUsername(username);
        if (password != NULL && password.length() > 0){
        //    kdDebug()<<"Showing stored password"<< password << endl;
            loginDialog->setPassword(password);
            //  kdDebug()<<"Showing stored password"<< password << endl;
        }
    }
    */

    QString username_edit, password_edit;

    if (!loginDialog)
    {
        kdDebug()<<" Out of memory error "<< endl;
    }

    if (loginDialog->exec() == QDialog::Accepted)
    {
        username_edit = loginDialog->username();
        password_edit = loginDialog->password();
    }
    else 
    {
        //Return something which say authentication needed.
        return ;
    }

    m_username    = username_edit;
    username_edit = username;
    QString accountType = "GOOGLE";

    if (!(username_edit.endsWith("@gmail.com")))
        username_edit += "@gmail.com";

    QByteArray buffer;
    QStringList qsl;
    qsl.append("Email="+username_edit);
    qsl.append("Passwd="+password_edit);
    qsl.append("accountType="+accountType);
    qsl.append("service=lh2");
    qsl.append("source=kipi-picasaweb-client");
    QString dataParameters = qsl.join("&");

    QTextStream ts(buffer, IO_Append|IO_WriteOnly);
    ts.setEncoding(QTextStream::UnicodeUTF8);
    ts << dataParameters;

    KIO::TransferJob* job = KIO::http_post(url, buffer, false);
    job->addMetaData("content-type", "Content-Type: application/x-www-form-urlencoded" );	
    m_state = FE_GETTOKEN;
    authProgressDlg->setLabelText(i18n("Getting the token"));

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)),
            this, SLOT(slotResult(KIO::Job *)));

    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy( true );
}

void PicasawebTalker::authenticate(const QString& token, const QString& username, const QString& password)
{
    if (!token || token.length() < 1)
    {
        checkToken(token);
        m_username = username;
        m_password = password; //this would be needed if the checktoken failed
                                //we would need to reauthenticate using auth
    }
    else 
    {
        getToken(username, password);
    }
}

void PicasawebTalker::checkToken(const QString& /*token*/) 
{
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    QString    url         = "https://www.google.com/accounts/ClientLogin";
    QString    auth_string = "GoogleLogin auth=" + m_token;
    QByteArray tmp;
    KIO::TransferJob* job  = KIO::http_post(url, tmp, false);
    job->addMetaData("customHTTPHeader", "Authorization: " + auth_string);

    job->addMetaData("content-type", "Content-Type: application/x-www-form-urlencoded");

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)),
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_CHECKTOKEN;
    authProgressDlg->setLabelText(i18n("Checking if previous token is still valid"));
    authProgressDlg->setProgress(1,4);
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy( true );
}

/** PicasaWeb's Album listing request/response
  * First a request is sent to the url below and then we might(?) get a redirect URL
  * WE then need to send the GET request to the Redirect url (this however gets taken care off by the 
  * KIO libraries.
  * This uses the authenticated album list fetching to get all the albums included the unlisted-albums
  * which is not returned for an unauthorised request as done without the Authorization header.
*/
void PicasawebTalker::listAllAlbums() {
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    QString    url = "http://picasaweb.google.com/data/feed/api/user/" + m_username + "?kind=album";
    QByteArray tmp;	
    QString auth_string = "GoogleLogin auth=" + m_token;
    KIO::TransferJob* job = KIO::get(url, tmp, false);
    job->addMetaData("content-type", "Content-Type: application/x-www-form-urlencoded" );	
    job->addMetaData("customHTTPHeader", "Authorization: " + auth_string );

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)), 
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_LISTALBUMS;
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy( true );

}

void PicasawebTalker::getPhotoProperty(const QString& method,const QString& argList)
{
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    QString     url="http://www.picasaweb.com/services/rest/?";
    QStringList headers;
    headers.append("api_key="+ m_apikey);
    headers.append("method="+method);
    headers.append("frob="+ m_frob);
    headers.append(argList);
    QString md5=getApiSig(m_secret,headers);
    headers.append("api_sig="+ md5);
    QString queryStr=headers.join("&");
    QString postUrl=url+queryStr;
    QByteArray tmp;	
    KIO::TransferJob* job = KIO::http_post(postUrl, tmp, false);
    job->addMetaData("content-type", "Content-Type: application/x-www-form-urlencoded" );	

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)), 
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_GETPHOTOPROPERTY;
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy( true );
    //authProgressDlg->setLabelText("Getting the Token from the server");
    //authProgressDlg->setProgress(3,4);
}

void PicasawebTalker::addPhotoTag(const QString& photoURI, const QString& tag)
{ 
    //if (m_job && m_state != FE_ADDTAG){ //we shouldn't kill the old tag request
    //	m_job->kill();
    //	m_job = 0;
    //}

    QString addTagXML = QString("<entry xmlns='http://www.w3.org/2005/Atom'> "
                                "<title>%1</title> "
                                "<category scheme='http://schemas.google.com/g/2005#kind' "
                                "term='http://schemas.google.com/photos/2007#tag'/> "
                                "</entry>").arg(tag);
    QString postUrl = QString("%1").arg(photoURI);
    QByteArray buffer;
    QTextStream ts(buffer, IO_Append|IO_WriteOnly);
    ts.setEncoding(QTextStream::UnicodeUTF8);
    ts << addTagXML;

    QString auth_string = "GoogleLogin auth=" + m_token;
    KIO::TransferJob* job = KIO::http_post(postUrl, buffer, false);
    job->addMetaData("content-type", "Content-Type: application/atom+xml");
    job->addMetaData("content-length", QString("Content-Length: %1").arg(addTagXML.length()));
    job->addMetaData("customHTTPHeader", "Authorization: " + auth_string );

    //connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
    //        this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)),
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_ADDTAG;
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy(true);
}

void PicasawebTalker::listPhotos(const QString& /*albumName*/)
{
    // TODO
}

void PicasawebTalker::createAlbum(const QString& albumTitle, const QString& albumDesc,
                                  const QString& location, uint  timestamp, const QString& access,
                                  const QString& media_keywords, bool isCommentsEnabled)
{
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    QString newAlbumXML = QString("<entry xmlns='http://www.w3.org/2005/Atom' "
                                "xmlns:media='http://search.yahoo.com/mrss/' "
                                "xmlns:gphoto='http://schemas.google.com/photos/2007'> "
                                "<title type='text'>%1</title> "
                                "<summary type='text'>%2</summary> "
                                "<gphoto:location>%3</gphoto:location> "
                                "<gphoto:access>%4</gphoto:access> "
                "<gphoto:commentingEnabled>%5</gphoto:commentingEnabled> "
                "<gphoto:timestamp>%6</gphoto:timestamp> "
                "<media:group> "
                "<media:keywords>%7</media:keywords> "
                "</media:group> "
                "<category scheme='http://schemas.google.com/g/2005#kind' "
                        "term='http://schemas.google.com/photos/2007#album'></category> "
                        "</entry> ").arg(albumTitle)
                                    .arg(albumDesc)
                                    .arg(location)
                                    .arg(access)
                                    .arg(isCommentsEnabled==true?"true":"false")
                                    .arg(timestamp)
                                    .arg(media_keywords);

    QByteArray buffer;
    QTextStream ts(buffer, IO_Append|IO_WriteOnly);
    ts.setEncoding(QTextStream::UnicodeUTF8);
    ts << newAlbumXML;

    MPForm form;
    QString postUrl = "http://www.picasaweb.google.com/data/feed/api/user/" + m_username ;
    QString auth_string = "GoogleLogin auth=" + m_token;
    KIO::TransferJob* job = KIO::http_post(postUrl, buffer, false);
    job->addMetaData("content-type", "Content-Type: application/atom+xml");
    job->addMetaData("content-length", QString("Content-Length: %1").arg(newAlbumXML.length()));
    job->addMetaData("customHTTPHeader", "Authorization: " + auth_string );

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)),
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_CREATEALBUM;
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy(true);
}

bool PicasawebTalker::addPhoto(const QString& photoPath, FPhotoInfo& info,
                               const QString& albumId, bool rescale,
                               int maxDim, int imageQuality)
{
    // Disabling this totally may be checking the m_state and doing selecting 
    // disabling is a better idea
    /*if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }*/

    QString album_id = albumId;

    if (album_id.length() == 0)
        album_id = "test";

    QString     postUrl = "http://www.picasaweb.google.com/data/feed/api/user/" + KURL::encode_string(m_username) + "/albumid/" + album_id;
    QString     path = postUrl;
    QStringList headers;
    MPForm      form;
    QString     auth_string = "GoogleLogin auth=" + m_token;

    //form.addPair("Authorization", auth_string);

    //Create the Body in atom-xml
    QStringList body_xml;
    body_xml.append("<entry xmlns=\'http://www.w3.org/2005/Atom\'>");
    body_xml.append("<title>"+ info.title +"</title>");
    body_xml.append("<summary>"+ info.description +"</summary>");
    body_xml.append("<category scheme=\"http://schemas.google.com/g/2005#kind\" "
                    "term=\"http://schemas.google.com/photos/2007#photo\" />");
    body_xml.append("</entry>");

    QString body = body_xml.join("");

    form.addPair("test", body, "application/atom+xml");

    // save the tags for this photo in to the tags hashmap
    tags_map.insert(info.title, info.tags); 
    QImage image;

    // Check if RAW file.
#if KDCRAW_VERSION < 0x000106
    QString rawFilesExt(KDcrawIface::DcrawBinary::instance()->rawFiles());
#else
    QString rawFilesExt(KDcrawIface::KDcraw::rawFiles());
#endif
    QFileInfo fileInfo(photoPath);
    if (rawFilesExt.upper().contains(fileInfo.extension(false).upper()))
        KDcrawIface::KDcraw::loadDcrawPreview(image, photoPath);
    else
        image.load(photoPath);

    if (!image.isNull())
    {
        path = locateLocal("tmp", QFileInfo(photoPath).baseName().stripWhiteSpace() + ".jpg");

        if (rescale && (image.width() > maxDim || image.height() > maxDim))
            image = image.smoothScale(maxDim, maxDim, QImage::ScaleMin);

        image.save(path, "JPEG", imageQuality);

        // Restore all metadata.

        KExiv2Iface::KExiv2 exiv2Iface;

        if (exiv2Iface.load(photoPath))
        {
            exiv2Iface.setImageProgramId(QString("Kipi-plugins"), QString(kipiplugins_version));
            exiv2Iface.setImageDimensions(image.size());
            exiv2Iface.save(path);
        }
        else
        {
            kdWarning(51000) << "(picasawebExport::Image doesn't have exif data)" << endl;
        }

        kdDebug() << "Resizing and saving to temp file: " << path << endl;
    }

    if (!form.addFile("photo", path))
        return false;

    form.finish();

    KIO::TransferJob* job = KIO::http_post(postUrl, form.formData(), false);
    job->addMetaData("content-type", form.contentType());	
    job->addMetaData("customHTTPHeader", "Authorization: " + auth_string );

    connect(job, SIGNAL(data(KIO::Job*, const QByteArray&)),
            this, SLOT(data(KIO::Job*, const QByteArray&)));

    connect(job, SIGNAL(result(KIO::Job *)),
            this, SLOT(slotResult(KIO::Job *)));

    m_state = FE_ADDPHOTO;
    m_job   = job;
    m_buffer.resize(0);
    emit signalBusy(true);
    return true;
}

QString PicasawebTalker::getUserName()
{
    return m_username;
}

QString PicasawebTalker::getUserId()
{
    return m_userId;
}

void PicasawebTalker::cancel()
{
    if (m_job)
    {
        m_job->kill();
        m_job = 0;
    }

    if (authProgressDlg && !authProgressDlg->isHidden()) 
        authProgressDlg->hide();
}

void PicasawebTalker::info(KIO::Job* /*job*/, const QString& /*str*/)
{
}

void PicasawebTalker::data(KIO::Job*, const QByteArray& data)
{
    if (data.isEmpty())
        return;

    int oldSize = m_buffer.size();
    m_buffer.resize(m_buffer.size() + data.size());
    QString output_data = QString(data);
    memcpy(m_buffer.data()+oldSize, data.data(), data.size());
}

void PicasawebTalker::slotError(const QString & error)
{
    QString transError;
    int     errorNo = 0;

    if (!error.isEmpty())
        errorNo = atoi(error.latin1());

    switch (errorNo)
    {
        case 2: 
            transError=i18n("No photo specified");break;
        case 3: 
            transError=i18n("General upload failure");break;
        case 4: 
            transError=i18n("Filesize was zero");break;
        case 5: 
            transError=i18n("Filetype was not recognised");break;
        case 6:
            transError=i18n("User exceeded upload limit");break;
        case 96:
            transError=i18n("Invalid signature"); break;
        case 97:
            transError=i18n("Missing signature"); break;
        case 98:
            transError=i18n("Login Failed / Invalid auth token"); break;
        case 100: 
            transError=i18n("Invalid API Key"); break;
        case 105:
            transError=i18n("Service currently unavailable");break;
        case 108:
            transError=i18n("Invalid Frob");break;
        case 111: 
            transError=i18n("Format \"xxx\" not found"); break;
        case 112: 
            transError=i18n("Method \"xxx\" not found"); break;
        case 114: 
            transError=i18n("Invalid SOAP envelope");break;
        case 115: 
            transError=i18n("Invalid XML-RPC Method Call");break;
        case 116: 
            transError=i18n("The POST method is now required for all setters"); break;
        default:
            transError=i18n("Unknown error");
    };

    KMessageBox::error(kapp->activeWindow(), i18n("Error Occured: %1\n We can not proceed further").arg(transError));
    //kdDebug()<<"Not handling the error now will see it later"<<endl;
}

void PicasawebTalker::slotResult(KIO::Job *job)
{
    m_job = 0;
    emit signalBusy(false);

    if (job->error())
    {
        if (m_state == FE_ADDPHOTO)
        {
            emit signalAddPhotoFailed(job->errorString());
        }
        else 
        {
            job->showErrorDialog(m_parent);
        }

        return;
    }

    switch(m_state)
    {
        case(FE_LOGIN):
            //parseResponseLogin(m_buffer);
            break;
        case(FE_CREATEALBUM):
            parseResponseCreateAlbum(m_buffer);
            break;
        case(FE_LISTALBUMS):
            parseResponseListAlbums(m_buffer);
            break;
        case(FE_GETFROB):
            break;
        case(FE_GETTOKEN):
            parseResponseGetToken(m_buffer);
            break;
        case(FE_CHECKTOKEN):
            parseResponseCheckToken(m_buffer);
            break;
        case(FE_GETAUTHORIZED):
            break;
        case(FE_LISTPHOTOS):
            parseResponseListPhotos(m_buffer);
            break;
        case(FE_GETPHOTOPROPERTY):
            parseResponsePhotoProperty(m_buffer);
            break;
        case(FE_ADDPHOTO):
            parseResponseAddPhoto(m_buffer);
            break;
        case(FE_ADDTAG):
            parseResponseAddTag(m_buffer);
            break;
    }
}

void PicasawebTalker::parseResponseCheckToken(const QByteArray &data)
{
    bool success = false;
    QString errorString;
    QString username;
    QString transReturn(data);
    // If checktoken failed.
    // getToken ...

    if(transReturn.startsWith("Error="))
        success = false;
    else
        success = true;

    if(!success)
        getToken(m_username, m_password);
    //emit signalError(errorString);
}

void PicasawebTalker::parseResponseGetToken(const QByteArray &data)
{
    bool success = false;
    QString errorString;
    QString str(data);
    //Check the response code should it be 200, proceed
    //if it is 403 handle the error mesg
    //figure out the auth string from this response

    if (str.find("Auth="))
    {
        QStringList strList = QStringList::split("Auth=", str);
        m_token = strList[1];
        success = 1;
    }

    if(success)
    {
        authProgressDlg->hide();
        emit signalTokenObtained(m_token);
    }
    else
    {
        emit signalError(errorString);
    }

    emit signalBusy(false);
}

void PicasawebTalker::getHTMLResponseCode(const QString& /*str*/)
{
}

void PicasawebTalker::parseResponseListAlbums(const QByteArray &data)
{
    bool success = false;
    QString str(data);
    QDomDocument doc( "feed" );
    if ( !doc.setContent( data ) ) 
    {
        return;
    }

    QDomElement docElem = doc.documentElement();
    QDomNode node = docElem.firstChild();
    QDomElement e;
    QString feed_id, feed_updated, feed_title, feed_subtitle;
    QString feed_icon_url, feed_link_url;
    QString feed_username, feed_user_uri;

    QString album_id, album_title, album_description;
    m_albumsList = new QValueList <PicasaWebAlbum>();

    while(!node.isNull())
    {
        if (node.isElement() && node.nodeName() == "entry")
        {
            success = true;
            e = node.toElement(); 
            QDomNode details=e.firstChild();
            PicasaWebAlbum fps;
            QDomNode detailsNode = details;

            while(!detailsNode.isNull())
            {
                if(detailsNode.isElement())
                {
                    if(detailsNode.nodeName() == "id")
                    {
			// The node data is a URL of which album id is the string following the last /
			// like <id>http://www.picasaweb.google.com/.../AlbumID<id>
			QString albumIdUrl = detailsNode.toElement().text();
                        int index = albumIdUrl.findRev("/");
                        int length = albumIdUrl.length();
                        QString album_id = albumIdUrl.right(length - index - 1);
                        fps.id = album_id;
                    }

                    if(detailsNode.nodeName() == "title")
                    {
                        album_title = "Not fetched";

                        if(detailsNode.toElement().attribute("type")=="text")
                            album_title = detailsNode.toElement().text();

                        //this is what is obtained from data.
                        fps.title = album_title;
                    }

                    if(detailsNode.nodeName()=="gphoto:name")
                    {
                        QString name = detailsNode.toElement().text();
                    }
                }

                detailsNode = detailsNode.nextSibling();
            }

            m_albumsList->append(fps);
        }

    node = node.nextSibling();
    }

    if (!success)
    {
        emit signalGetAlbumsListFailed(i18n("Failed to fetch photoSets List"));
        m_albumsList = NULL;
    }
    else
    {
        emit signalGetAlbumsListSucceeded();
    }
}

void PicasawebTalker::parseResponseListPhotos(const QByteArray &data)
{
    QDomDocument doc( "getPhotosList" );
    if ( !doc.setContent( data ) ) 
    {
        return;
    }

    QDomElement docElem = doc.documentElement();
    QDomNode node = docElem.firstChild();
    //QDomElement e;
    // TODO
}

void PicasawebTalker::parseResponseCreateAlbum(const QByteArray &data)
{
    bool success = false;
    QString errorString;
    QString response(data);
    QDomDocument doc( "AddPhoto Response" );
    // parse the new album name
    QDomElement docElem = doc.documentElement();
    QString title, photo_id, album_id, photoURI; 
    QDomNode node = docElem.firstChild(); //this should mean <entry>
    QDomElement e;

    while( !node.isNull() ) 
    {
        if ( node.isElement()) 
        {
            QString node_name = node.nodeName();
            QString node_value = node.toElement().text();
            if(node_name == "title")
            {
                success = true;
                title = node_value;
            }
            else if (node_name == "id")
                photoURI = node_value;
            else if(node_name == "gphoto:id")
                photo_id = node_value;
            else if(node_name == "gphoto:albumid")
                album_id = node_value;
        }

        node = node.nextSibling();
    }

    // Raise a popup informing success
}

void PicasawebTalker::parseResponseAddTag(const QByteArray &data)
{
    QString str(data);
    remaining_tags_count -= 1;
    emit signalBusy( false );
    m_buffer.resize(0);

    if (remaining_tags_count == 0)
        emit signalAddPhotoSucceeded();
}

void PicasawebTalker::parseResponseAddPhoto(const QByteArray &data)
{
    bool success = false;
    QString     line;
    QString str(data);
    success = 1;
    QDomDocument doc( "AddPhoto Response" );

    if ( !doc.setContent( data ) ) 
    {
        return;
    }

    QDomElement docElem = doc.documentElement();
    QString title, photo_id, album_id, photoURI; 
    QDomNode node = docElem.firstChild(); //this should mean <entry>
    QDomElement e;

    while( !node.isNull() ) 
    {
        if ( node.isElement()) 
        {
            QString node_name = node.nodeName();
            QString node_value = node.toElement().text();
            if(node_name == "title")
            {
                success = true;
                title = node_value;
            }
            else if (node_name == "id")
                photoURI = node_value;
            else if(node_name == "gphoto:id")
                photo_id = node_value;
            else if(node_name == "gphoto:albumid")
                album_id = node_value;
        }

        node = node.nextSibling();
    }

    if (!success)
    {
        emit signalAddPhotoFailed(i18n("Failed to upload photo"));
    }
    else
    {
        // Update the tags information from the tags_map
        QStringList tags = tags_map[title];
        remaining_tags_count = tags.count();

        if (tags.count() == 0)
            emit signalAddPhotoSucceeded();

        for ( QStringList::Iterator it = tags.begin(); it != tags.end(); ++it ) 
        {
            QString photoURI= QString("http://picasaweb.google.com/data/feed/api/user/"
                    "%1/albumid/%2/photoid/%3").arg(m_username).arg(album_id).arg(photo_id);
            addPhotoTag( photoURI, *it);
        }
    }
}

void PicasawebTalker::parseResponsePhotoProperty(const QByteArray &data)
{
    bool success = false;
    QString     line;
    QDomDocument doc( "Photos Properties" );

    if ( !doc.setContent( data ) ) 
    {
        return;
    }

    QDomElement docElem = doc.documentElement();
    QDomNode node = docElem.firstChild();
    QDomElement e;

    while( !node.isNull() ) 
    {
        if ( node.isElement() && node.nodeName() == "photoid" ) 
        {
            e = node.toElement(); // try to convert the node to an element.
            QDomNode details=e.firstChild();
            success=true;
        }

        if ( node.isElement() && node.nodeName() == "err" ) 
        {
            kdDebug()<<"Checking Error in response"<<endl;
            QString code=node.toElement().attribute("code");
            kdDebug()<<"Error code="<<code<<endl;
            kdDebug()<<"Msg="<<node.toElement().attribute("msg")<<endl;	
            emit signalError(code);
        }
        node = node.nextSibling();
    }

    kdDebug()<<"GetToken finished"<<endl;
    if (!success)
    {
        emit signalAddPhotoFailed(i18n("Failed to query photo information"));
    }
    else
    {
        //emit signalAddPhotoSucceeded();
    }
}

} // KIPIPicasawebExportPlugin