Logo Search packages:      
Sourcecode: kblogger-kde4 version File versions  Download package

weblogstylegetter.cpp

/***************************************************************************

   Copyright (C) 2005-2007 by Christian Weilbach <christian_weilbach@web.de>
   Copyright (C) 2007 Antonio Aloisio <gnuton@gnuton.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.

   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, write to the
   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
 ***************************************************************************/

#include "weblogstylegetter.h"

#include <kio/job.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kdatetime.h>
#include <klocale.h>
#include <kdebug.h>

#include <QFile>

#include "kbloggerpost.h"
#include "backend.h"
#include "kbloggermedia.h"

#define POST_TITLE "Temporary-Post-Used-For-Style-Detection-Title-"
#define POST_CONTENT "Temporary-Post-Used-For-Style-Detection-Content-"
#define DIR_TO_SAVE_ENTRIES "styles/"

namespace KBlogger
{

WeblogStyleGetter::WeblogStyleGetter(const QString &blog, QObject *parent): QObject(parent)
{
    //Sets cachePath to ~/.kde4/share/apps/kblogger/styles/my_blog_name
    cachePath = KStandardDirs::locateLocal("appdata", DIR_TO_SAVE_ENTRIES + blog + '/' , true);
    generateRandomPostStrings();
    mParent = qobject_cast<QWidget*>(parent);
    Q_ASSERT(mParent);
    //1. Create Temp Post
    kDebug();
    QStringList categories("");
    tempPost = new KBloggerPost(blog,
                                postTitle,  //title
                                postContent, //content
                                categories, //category
                                false, //isPrivate
                                KDateTime(QDateTime(QDate(2000,1,1),QTime(0,0)))//datetime
                               );
    Backend::self()->disconnect(SIGNAL(jobsFinished()));
    connect ( Backend::self() , SIGNAL(jobsFinished()), SLOT(slotPostSent()) );

    //2. Send post
    Backend::self()->sendPost(tempPost, mParent);
    Backend::self()->runQueuedJobs();
};

WeblogStyleGetter::~WeblogStyleGetter()
{
    kDebug();
};

QString WeblogStyleGetter::styledHtml(const QString& blogname,
                                      const QString &title,
                                      const QString &content)
{
    kDebug();
    QString url = QString("%1%2/index.html").arg(DIR_TO_SAVE_ENTRIES).arg(blogname);
    QString basePath = KBloggerMedia::cachePath();
    KUrl dest = KStandardDirs::locate("appdata", url);
    kDebug() << dest << url;
    QString buffer;
    if ( !dest.isValid() ) {
        return "<html><head><base href=\"" + basePath + "\" /></head><body><b>" + title + "</b><br>" + content + "</html>";
    }
    QFile file( dest.path() );
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return "<html><body><b>" + title + "</b><br>" + content + "</html>";
    }
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        buffer.append(line);
    }

//     QRegExp headRx("<head[\\s]?([\\d\\w]*=\"?[\\d\\w:\\/.]*\"?)?>");
    QRegExp titleRx(QString("%1[\\d]*").arg(POST_TITLE));
    QRegExp contentRx(QString("%1[\\d]*").arg(POST_CONTENT));

//     buffer.replace(headRx, "<head><base href=\"" + basePath + "\"/>");
    buffer.replace(titleRx, title);
    buffer.replace(contentRx, content);

    return buffer;
};

void WeblogStyleGetter::slotPostSent()
{
    kDebug();
    Backend::self()->disconnect(SIGNAL(jobsFinished()));
    connect ( Backend::self() , SIGNAL(jobsFinished()), SLOT(slotPostFetched()) );
    Backend::self()->fetchPost(tempPost, mParent);
    Backend::self()->runQueuedJobs();
};

void WeblogStyleGetter::slotPostFetched()
{
    kDebug();

    Backend::self()->disconnect(SIGNAL(jobsFinished()));
    //3.Read post url
    KUrl src(tempPost->link());

    kDebug() << "Retrieving" << src;
    //4.Copy post in the cache
    httpGetJob = KIO::storedGet(src, KIO::NoReload, KIO::HideProgressInfo);

    connect( httpGetJob, SIGNAL( result( KJob* ) ),
             this, SLOT( slotHtmlCopied( KJob* ) ) );
}

void WeblogStyleGetter::slotHtmlCopied(KJob *job)
{
    kDebug();
    if ( job->error() ) {
        KMessageBox::error( 0,
                            i18n("Impossible to get html file,%1", job->errorString()));
        return;
    }
    QByteArray httpData( dynamic_cast<KIO::StoredTransferJob*>(job)->data() );

    // KUrl directory() hasn't worked for me, so i do it myself:
    QString href( tempPost->link().url() );
    int filenameOffset = href.lastIndexOf( "/" );
    href = href.remove( filenameOffset+1, 255 );
    QString base( "<base href=\""+href+"\"/>" );
    kDebug()<< "base: " << base;

    QRegExp rxBase( "(<base\\shref=[^>]+>)" ); // TODO check if that works
    if( rxBase.indexIn( httpData ) != -1 ){
         httpData.replace( rxBase.cap(1).toLatin1(), base.toLatin1() );
    }
    else {
        int headOffset = httpData.indexOf( "<head>" );
        httpData.insert( headOffset+6, base.toLatin1() );
    }

    KUrl dest(cachePath + "index.html");
    Q_ASSERT( dest.isValid() );
    QFile file(dest.path());
    file.open(QIODevice::WriteOnly);
    if ( file.write(httpData) == -1 ) {
        KMessageBox::error( 0,
                            i18n("Impossible to write data to file %1", dest.path()));
        file.close();
        return;
    }
    file.close();
    emit styleFetched();

    //Remove temp post from the server.
    Backend::self()->removePost(tempPost, mParent);
    Backend::self()->runQueuedJobs();
};

void WeblogStyleGetter::generateRandomPostStrings()
{
    kDebug();
    srand(time(0));
    int postRandomNumber = rand();
    postTitle = QString("%1%2").arg(POST_TITLE).arg( postRandomNumber );
    postContent = QString("%1%2").arg(POST_CONTENT).arg( postRandomNumber );
};

}; //namespace
#include "weblogstylegetter.moc"

Generated by  Doxygen 1.6.0   Back to index