~ubuntu-branches/ubuntu/oneiric/kdepim/oneiric-updates

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
/*
    This file is part of Blogilo, A KDE Blogging Client

    Copyright (C) 2008-2010 Mehrdad Momeny <mehrdad.momeny@gmail.com>
    Copyright (C) 2008-2010 Golnaz Nilieh <g382nilieh@gmail.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 of
    the License or (at your option) version 3 or any later version
    accepted by the membership of KDE e.V. (or its successor approved
    by the membership of KDE e.V.), which shall act as a proxy
    defined in Section 14 of version 3 of the license.


    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.

    You should have received a copy of the GNU General Public License
    along with this program; if not, see http://www.gnu.org/licenses/
*/

#include "backend.h"
#include "bilboblog.h"
#include "bilbopost.h"
#include "bilbomedia.h"
#include "dbman.h"

#include <kurl.h>
#include <kblog/blogger1.h>
#include <kblog/gdata.h>
#include <kblog/metaweblog.h>
#include <kblog/movabletype.h>
#include <kblog/wordpressbuggy.h>
#include <kblog/blogmedia.h>
#include <kdebug.h>
#include <KDE/KLocale>
// #include <QMimeData>
#include <kio/netaccess.h>
#include <kio/job.h>
#include <settings.h>

const QRegExp splitRX("((<hr/?>)?<!--split-->)");

class Backend::Private
{
public:
    Private()
    :categoryListNotSet(false)
    {}
    KBlog::Blog *kBlog;
    BilboBlog *bBlog;
//     quint16 mChecksum;
//     QString mediaLocalUrl;
    QList<Category> mCreatePostCategories;
    QMap<QString, KBlog::BlogPost *> mSetPostCategoriesMap;
    QMap<KBlog::BlogPost *, BilboPost::Status> mSubmitPostStatusMap;
    QMap<KBlog::BlogMedia *, BilboMedia *> mPublishMediaMap;
    bool categoryListNotSet;
};

Backend::Backend( int blog_id, QObject* parent )
: QObject( parent ), d(new Private)
{
    kDebug() << "with blog id: " << blog_id;
    d->bBlog = DBMan::self()->blog( blog_id );
    d->kBlog = d->bBlog->blogBackend();

    connect( d->kBlog, SIGNAL( error( KBlog::Blog::ErrorType, const QString& ) ),
             this, SLOT( error( KBlog::Blog::ErrorType, const QString& ) ) );
    connect( d->kBlog, SIGNAL( errorPost( KBlog::Blog::ErrorType, const QString &, KBlog::BlogPost* ) ),
             this, SLOT( error( KBlog::Blog::ErrorType, const QString& ) ) );
    connect( d->kBlog, SIGNAL( errorComment( KBlog::Blog::ErrorType, const QString &, KBlog::BlogPost*,
                                           KBlog::BlogComment* ) ),
             this, SLOT( error( KBlog::Blog::ErrorType, const QString& ) ) );
    connect( d->kBlog, SIGNAL( errorMedia( KBlog::Blog::ErrorType, const QString &, KBlog::BlogMedia* ) ),
             this, SLOT( error( KBlog::Blog::ErrorType, const QString& ) ) );
}

Backend::~Backend()
{
    kDebug();
    delete d;
}

void Backend::getCategoryListFromServer()
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    if ( d->bBlog->api() == BilboBlog::METAWEBLOG_API || d->bBlog->api() == BilboBlog::MOVABLETYPE_API ||
         d->bBlog->api() == BilboBlog::WORDPRESSBUGGY_API ) {
        KBlog::MetaWeblog *tmp = dynamic_cast<KBlog::MetaWeblog*>( d->kBlog );
        connect( tmp, SIGNAL( listedCategories( const QList< QMap< QString, QString > > & ) ),
                 this, SLOT( categoriesListed( const QList< QMap< QString, QString > > & ) ) );
        tmp->listCategories();
    } else {
        char err[] = "Blog API doesn't support getting Category list.";
        kDebug() << err;
        error( KBlog::Blog::NotSupported, i18n( err ) );
    }
}

void Backend::categoriesListed( const QList< QMap < QString , QString > > & categories )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    DBMan::self()->clearCategories( d->bBlog->id() );

    for ( int i = 0; i < categories.count(); ++i ) {
        QString name, description, htmlUrl, rssUrl, categoryId, parentId;
        const QMap<QString, QString> &category = categories.at( i );

        name = category.value( "name", QString() );
        description = category.value( "description", QString() );
        htmlUrl = category.value( "htmlUrl", QString() );
        rssUrl = category.value( "rssUrl", QString() );
        categoryId = category.value( "categoryId", QString() );
        parentId = category.value( "parentId", QString() );

        if(categoryId.isEmpty()) {
            categoryId = QString::number(i);
        }

        DBMan::self()->addCategory( name, description, htmlUrl, rssUrl, categoryId, parentId, d->bBlog->id() );
    }
    kDebug() << "Emitting sigCategoryListFetched...";
    Q_EMIT sigCategoryListFetched( d->bBlog->id() );
}

void Backend::getEntriesListFromServer( int count )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    connect( d->kBlog, SIGNAL( listedRecentPosts( const QList<KBlog::BlogPost> & ) ),
             this, SLOT( entriesListed( const QList<KBlog::BlogPost >& ) ) );
    d->kBlog->listRecentPosts( count );
}

void Backend::entriesListed( const QList< KBlog::BlogPost > & posts )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
//     DBMan::self()->clearPosts( d->bBlog->id() );

    for ( int i = 0; i < posts.count(); i++ ) {
        BilboPost tempPost( posts[i] );
        if(Settings::changeNToBreak()) {
            tempPost.setContent( tempPost.content().replace( '\n', "<br/>" ) );
            tempPost.setAdditionalContent( tempPost.additionalContent().replace( '\n', "<br/>" ) );
        }
        DBMan::self()->addPost( tempPost, d->bBlog->id() );
    }
    kDebug() << "Emitting sigEntriesListFetched ...";
    Q_EMIT sigEntriesListFetched( d->bBlog->id() );
}

void Backend::publishPost( BilboPost* post )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
//     BilboPost tmpPost = post;
    if( Settings::addPoweredBy() ) {
        QString poweredStr = "<p>=-=-=-=-=<br/>"
        "<i>Powered by <b><a href='http://blogilo.gnufolks.org/'>Blogilo</a></b></i></p>";
        post->setContent(post->content() + poweredStr);
    }
    preparePost( post );
    connect( d->kBlog, SIGNAL( createdPost( KBlog::BlogPost * ) ),
             this, SLOT( postPublished( KBlog::BlogPost * ) ) );
    d->kBlog->createPost( post );
}

void Backend::postPublished( KBlog::BlogPost *post )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    if ( post->status() == KBlog::BlogPost::Error ) {
        kDebug() << "Publishing/Modifying Failed";
        const QString tmp( i18n( "Publishing/Modifying post failed: %1", post->error() ) );
        kDebug() << "Emitting sigError...";
        Q_EMIT sigError( tmp );
        return;
    }
    kDebug()<<"isPrivate: "<<post->isPrivate();
    if(post->isPrivate() && d->bBlog->api() == BilboBlog::GDATA_API){
        //GData do not support fetching drafts!
        savePostInDbAndEmitResult(post);
        return;
    }
    d->mSubmitPostStatusMap[ post ] = post->status();
    connect( d->kBlog, SIGNAL( fetchedPost(KBlog::BlogPost*)),
             this, SLOT( savePostInDbAndEmitResult(KBlog::BlogPost*)) );
    d->kBlog->fetchPost( post );
}

void Backend::uploadMedia( BilboMedia * media )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    QString tmp;
    switch ( d->bBlog->api() ) {
        case BilboBlog::BLOGGER1_API:
        case BilboBlog::GDATA_API:
            kDebug() << "The Blogger1 and GData API type doesn't support uploading Media files.";
            tmp = i18n( "Uploading media failed: Your Blog API does not support uploading media objects.");
            kDebug() << "Emitting sigError...";
            Q_EMIT sigMediaError( tmp, media );
            return;
            break;
        case BilboBlog::METAWEBLOG_API:
        case BilboBlog::MOVABLETYPE_API:
        case BilboBlog::WORDPRESSBUGGY_API:
            KBlog::BlogMedia *m = new KBlog::BlogMedia() ;
            KBlog::MetaWeblog *MWBlog = qobject_cast<KBlog::MetaWeblog*>( d->kBlog );

            m->setMimetype( media->mimeType() );

            QByteArray data;
            KIO::TransferJob *job = KIO::get( media->localUrl(), KIO::Reload, KIO::HideProgressInfo);
            if( !KIO::NetAccess::synchronousRun(job, 0, &data) ){
                kError()<<"Job error: " << job->errorString();
                tmp = i18n( "Uploading media failed: Cannot read the media file,\
 please check if it exists. Path: %1", media->localUrl().pathOrUrl() );
                kDebug() << "Emitting sigError...";
                Q_EMIT sigMediaError( tmp, media );
            }

            if ( data.count() == 0 ) {
                kError() << "Cannot read the media file, please check if it exists.";
                tmp = i18n( "Uploading media failed: Cannot read the media file,\
 please check if it exists. Path: %1", media->localUrl().pathOrUrl() );
                kDebug() << "Emitting sigError...";
                Q_EMIT sigMediaError( tmp, media );
                return;
            }

            m->setData( data );
            m->setName( media->name() );

            media->setCheckSum( qChecksum( data.data(), data.count() ) );

            if ( media->checksum() == 0 ) {
                kError() << "Media file checksum is zero";
                tmp = i18n( "Uploading media failed: Media file checksum is zero, please check file path. Path: %1",
                                         media->localUrl().pathOrUrl() );
                kDebug() << "Emitting sigError...";
                Q_EMIT sigMediaError( tmp, media );
                return;
            }

            if ( !MWBlog ) {
                kError() << "MWBlog is NULL: casting has not worked, this should NEVER happen, has the gui allowed using GDATA?";
                tmp = i18n( "INTERNAL ERROR: MWBlog is NULL: casting has not worked, this should NEVER happen." );
                kDebug() << "Emitting sigError...";
                Q_EMIT sigError( tmp );
                return;
            }
            d->mPublishMediaMap[ m ] = media;
            connect( MWBlog, SIGNAL( createdMedia( KBlog::BlogMedia* ) ), this, SLOT( mediaUploaded( KBlog::BlogMedia* ) ) );
            connect( MWBlog, SIGNAL( errorMedia( KBlog::Blog::ErrorType, const QString &, KBlog::BlogMedia* ) ),
                     this, SLOT( slotMediaError( KBlog::Blog::ErrorType, const QString &, KBlog::BlogMedia* ) ) );
            MWBlog->createMedia( m );
            return;
            break;
    }
    kError() << "Api type isn't set correctly!";
    tmp = i18n( "API type is not set correctly." );
    Q_EMIT sigError( tmp );
}

void Backend::mediaUploaded( KBlog::BlogMedia * media )
{
    kDebug() << "Blog Id: " << d->bBlog->id() << "Media: "<<media->url();
    if(!media){
        kError()<<"ERROR! Media returned from KBlog is NULL!";
        return;
    }
    BilboMedia * m = d->mPublishMediaMap.value( media );
    if(!m){
        kError()<<"ERROR! Media returned from KBlog doesn't exist on the Map! Url is:"
                << media->url();
        return;
    }
    d->mPublishMediaMap.remove( media );
    if ( media->status() == KBlog::BlogMedia::Error ) {
        kError() << "Upload error! with this message: " << media->error();
        const QString tmp( i18n( "Uploading media failed: %1", media->error() ) );
        kDebug() << "Emitting sigMediaError ...";
        Q_EMIT sigMediaError( tmp, m );
        return;
    }
    quint16 newChecksum = qChecksum( media->data().data(), media->data().count() );
    if ( newChecksum != m->checksum() ) {
        kError() << "Check sum error: checksum of sent file: " << m->checksum() <<
                " Checksum of received file: " << newChecksum << "Error: " << media->error() << endl;
        const QString tmp( i18n( "Uploading media failed: Checksum error. Returned error: %1",
                           media->error() ) );
        kDebug() << "Emitting sigMediaError ...";
        Q_EMIT sigMediaError( tmp, m );
        return;
    }
    m->setRemoteUrl( QUrl( media->url().url() ).toString() );
    m->setUploaded( true );
    kDebug() << "Emitting sigMediaUploaded...";
    Q_EMIT sigMediaUploaded( m );
}

void Backend::modifyPost( BilboPost* post )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
//     BilboPost tmpPost = post;
    preparePost( post );
    connect( d->kBlog, SIGNAL( modifiedPost(KBlog::BlogPost*)),
             this, SLOT( postPublished(KBlog::BlogPost*)) );
    d->kBlog->modifyPost( post );
}

void Backend::removePost( BilboPost* post )
{
    kDebug() << "Blog Id: " << d->bBlog->id();

//     KBlog::BlogPost *bp = post.toKBlogPost();
    connect( d->kBlog, SIGNAL( removedPost(KBlog::BlogPost*)),
             this, SLOT( slotPostRemoved(KBlog::BlogPost*)) );
    d->kBlog->removePost( post );
}

void Backend::slotPostRemoved( KBlog::BlogPost *post )
{
    if(!post) {
        kDebug()<<"post returned from server is NULL";
        return;
    }
    if( !DBMan::self()->removePost(d->bBlog->id(), post->postId()) ) {
        kDebug()<<"cannot remove post from database, error: "<<DBMan::self()->lastErrorText();
    }
    emit sigPostRemoved(d->bBlog->id(), BilboPost(*post));
}

void Backend::fetchPost( BilboPost* post )
{
//     KBlog::BlogPost *bp = post.toKBlogPost();
    connect( d->kBlog, SIGNAL( fetchedPost(KBlog::BlogPost*)),
             this, SLOT( slotPostFetched(KBlog::BlogPost*)) );
    d->kBlog->fetchPost( post );
}

void Backend::slotPostFetched( KBlog::BlogPost *post )
{
    emit sigPostFetched( new BilboPost(*post) );
//     delete post;
}

void Backend::error( KBlog::Blog::ErrorType type, const QString & errorMessage )
{
    kDebug() << "Blog Id: " << d->bBlog->id();
    QString errType = errorTypeToString( type );
    errType += errorMessage;
    kDebug() << errType;
    kDebug() << "Emitting sigError";
    Q_EMIT sigError( errType );
}

void Backend::slotMediaError( KBlog::Blog::ErrorType type, const QString & errorMessage,
                              KBlog::BlogMedia * media )
{
    kDebug();
    QString errType = errorTypeToString( type );
    errType += errorMessage;
    kDebug() << errType;
    kDebug() << "Emitting sigMediaError ...";
    emit sigMediaError( errorMessage, d->mPublishMediaMap[ media ] );
    d->mPublishMediaMap.remove( media );
}

QString Backend::errorTypeToString( KBlog::Blog::ErrorType type )
{
    QString errType;
    switch ( type ) {
        case KBlog::Blog::XmlRpc:
            errType = i18n( "Server (XMLRPC) error: " );
            break;
        case KBlog::Blog::Atom:
            errType = i18n( "Server (Atom) error: " );
            break;
        case KBlog::Blog::ParsingError:
            errType = i18n( "Parsing error: " );
            break;
        case KBlog::Blog::AuthenticationError:
            errType = i18n( "Authentication error: " );
            break;
        case KBlog::Blog::NotSupported:
            errType = i18n( "Not supported error: " );
            break;
        default:
            errType = i18n( "Unknown error: " );
    };
    return errType;
}

void Backend::savePostInDbAndEmitResult( KBlog::BlogPost *post )
{
    if(!post) {
        kError()<<"ERROR: post is NULL ";
        Q_EMIT sigError( "post is NULL" );
        return;
    }
    kDebug()<<"isPrivate: "<<post->isPrivate();
    BilboPost *pp = new BilboPost( *post );
    int post_id;
    if( d->mSubmitPostStatusMap[ post ] == KBlog::BlogPost::Modified) {
        post_id = DBMan::self()->editPost( *pp, d->bBlog->id() );
    } else {
        post_id = DBMan::self()->addPost( *pp, d->bBlog->id() );
    }
    d->mSubmitPostStatusMap.remove(post);
    if ( post_id != -1 ) {
        pp->setPrivate( post->isPrivate() );
        pp->setId( post_id );
        kDebug() << "Emitting sigPostPublished ...";
        Q_EMIT sigPostPublished( d->bBlog->id(), pp );
    }
    // TODO crashes stylegetter on GData. Somehow the post gets deleted before
    // slotFetchedPost as it seems. Don't get all the pointer copies done here.
    //delete post;
}

KBlog::BlogPost* Backend::preparePost( KBlog::BlogPost* post )
{
    QString content = post->content();
    QString html1 = QString();
    int i = 0;
    int found = content.indexOf("<pre>", i, Qt::CaseInsensitive);
    while ( found != -1 )
    {
    html1 += content.mid( i, found-i).remove('\n');
    i = found;
    found = content.indexOf("</pre>", i, Qt::CaseInsensitive);
    if ( found != -1 ) {
        html1 += content.mid( i, found+5-i);
        i = found + 5;
        found = content.indexOf("<pre>", i, Qt::CaseInsensitive);
    } else {
        html1 += content.mid( i, content.length()-i );
        i = -1;
    }
    }
    if ( i != -1 )
    html1 += content.mid( i, content.length()-i).remove('\n');
    post->setContent( html1 );

    content = post->additionalContent();
    QString html2 = QString();
    i= 0;
    found = content.indexOf("<pre>", i, Qt::CaseInsensitive);
    while ( found != -1 )
    {
    html2 += content.mid( i, found-i).remove('\n');
    i = found;
    found = content.indexOf("</pre>", i, Qt::CaseInsensitive);
    if ( found != -1 ) {
        html2 += content.mid( i, found+5-i);
        i = found + 5;
        found = content.indexOf("<pre>", i, Qt::CaseInsensitive);
    } else {
        html2 += content.mid( i, content.length()-i );
        i = -1;
    }
    }
    if ( i != -1 )
    html2 += content.mid( i, content.length()-i).remove('\n');
    post->setAdditionalContent( html2 );

    //the following two lines are replaced by the above code, because '\n' characters shouldn't
    //be omitted inside <pre> blocks.

    //post.setContent( post.content().remove('\n') );
    //post.setAdditionalContent( post.additionalContent().remove( '\n' ) );
    if ( d->bBlog->api() == BilboBlog::MOVABLETYPE_API || d->bBlog->api() == BilboBlog::WORDPRESSBUGGY_API ) {
        QStringList content = post->content().split(splitRX);
        if( content.count() == 2 ) {
            post->setContent(content[0]);
            post->setAdditionalContent( content[1] );
        }
    }
//     if( d->bBlog->api() == BilboBlog::MOVABLETYPE_API && post.categoryList().count() > 0 ) {
//         mCreatePostCategories = post.categoryList();
//         categoryListNotSet = true;
//     }
    return post;//.toKBlogPost();
}

#include "backend.moc"