akabeibackend.cpp 22.2 KB
Newer Older
Dario Freddi's avatar
Dario Freddi committed
1 2 3
/* This file is part of the Chakra project

   Copyright (C) 2010 Dario Freddi <drf@chakra-project.org>
4
   Copyright (C) 2012 Lukas Appelhans <boom1992@chakra-project.org>
Dario Freddi's avatar
Dario Freddi committed
5 6 7 8 9 10 11

   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.
*/

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <akabeibackend_p.h>

#include <akabeiconfig.h>
#include <akabeidatabase.h>
#include <akabeigroup.h>
#include <akabeipackage_p.h>
#include <akabeihelpers_p.h>
#include <akabeidelta_p.h>
#include <akabeigroup_p.h>

#include <QHash>
#include <QtConcurrentRun>
#include <QtConcurrentMap>
#include <QDir>
#include <QFutureWatcher>
27
#include <QVariant>
28

29 30
#include <libarchive++/archivehandler.h>
#include <akabeihook.h>
31
#include <fcntl.h>
32

Dario Freddi's avatar
Dario Freddi committed
33 34 35 36
Q_DECLARE_METATYPE(QUuid)
Q_DECLARE_METATYPE(QList< Akabei::Package* >)
Q_DECLARE_METATYPE(QList< Akabei::Group* >)

37 38 39
namespace Akabei
{

40
// For concurrent queries
41 42
struct ConcurrentPackageQuery
{
Daniele Cocca's avatar
Daniele Cocca committed
43 44 45 46
    ConcurrentPackageQuery(QString const& sql)
      : m_sql( sql )
    {
    }
47 48 49

    typedef QList< Package* > result_type;

50 51 52 53
    QList< Package* > operator()(Database *db)
    {
        return db->queryPackages(m_sql);
    }
54 55 56 57 58 59

    QString m_sql;
};

struct ConcurrentGroupQuery
{
Daniele Cocca's avatar
Daniele Cocca committed
60 61 62 63
    ConcurrentGroupQuery(QString const& sql)
      : m_sql( sql )
    {
    }
64 65 66

    typedef QList< Group* > result_type;

67 68 69 70
    QList< Group* > operator()(Database *db)
    {
        return db->queryGroups(m_sql);
    }
71 72 73 74

    QString m_sql;
};

75
QHash<QString, Database*> BackendPrivate::performInitialization()
76
{
77
    Q_Q(Backend);
78 79
    QHash<QString, Database*> rethash;

80
    // Check for the existence of all the needed directories
81 82
    QDir dbDir(Config::instance()->databasePath());
    if (!dbDir.exists()) {
Lukas Appelhans's avatar
Lukas Appelhans committed
83
        qWarning() << "Database dir does not exist";
84
        // Fail
85 86 87 88 89
        return QHash<QString, Database*>();
    }

    QDir cacheDir(Config::instance()->cachePath());
    if (!cacheDir.exists()) {
Lukas Appelhans's avatar
Lukas Appelhans committed
90
        qWarning() << "Cache dir does not exist";
91
        // Fail
92 93 94 95 96
        return QHash<QString, Database*>();
    }

    QDir rootDir(Config::instance()->root());
    if (!rootDir.exists()) {
Lukas Appelhans's avatar
Lukas Appelhans committed
97
        qWarning() << "Root dir does not exist";
98
        // Fail
99 100 101
        return QHash<QString, Database*>();
    }

102 103
    Database* localDb = q->loadDatabaseFromFile(dbDir.absoluteFilePath("local.db"));
    if (!localDb) {
104
        // Fail
105 106 107
        return QHash<QString, Database*>();
    }

108
    // Ok, add it to our rethash
109 110
    rethash.insert("local", localDb);

111
    // Now process all the various databases
Daniele Cocca's avatar
Daniele Cocca committed
112
    foreach (QString const& db, Config::instance()->databases()) {
113
        Database* database = q->loadDatabaseFromFile(dbDir.absoluteFilePath(db + ".db"));
114

115
        // Ok, add it to our rethash
116 117
        if (database)
            rethash.insert(db, database);
118 119
    }

120
    // Return it straight
121
    return rethash;
122
}
123

124 125
void BackendPrivate::addDatabase(const QString &name)
{
126
    Q_Q(Backend);
Daniele Cocca's avatar
Daniele Cocca committed
127
    if (name == "local") {
128
        return;
Daniele Cocca's avatar
Daniele Cocca committed
129
    }
130

131
    Database * database = q->loadDatabaseFromFile(Akabei::Config::instance()->databaseDir().absoluteFilePath(name + ".db"));
132

133 134
    if (database)
        databases.append(database);
135 136
}

137 138 139 140 141 142 143 144 145 146
void BackendPrivate::setStatus(Backend::Status s)
{
    Q_Q(Backend);

    if (s != status) {
        status = s;
        emit q->statusChanged(status);
    }
}

147
void BackendPrivate::__k__initializationFinished()
148 149 150 151
{
    databases.clear();
    localDatabase = 0;

152
    // Let's see what we got
153
    QHash< QString, Database* > const& rethash = initializationWatcher->result();
154

155
    // Delete the watcher
156 157 158
    initializationWatcher->deleteLater();

    if (rethash.isEmpty()) {
159
        // Broken
160 161 162 163 164 165
        setStatus(Akabei::Backend::StatusBroken);
        return;
    }

    localDatabase = rethash["local"];
    if (!localDatabase) {
166
        // Something very wrong here
167 168 169 170
        setStatus(Akabei::Backend::StatusBroken);
        return;
    }

171
    // All the rest
172 173
    for (QHash< QString, Database* >::const_iterator i = rethash.constBegin(); i != rethash.constEnd(); ++i) {
        if (i.key() == "local") {
174
            // Skip
175 176 177 178 179 180
            continue;
        }

        databases.append(i.value());
    }

181
    // The backend is now ready
182 183 184
    setStatus(Akabei::Backend::StatusReady);
}

185 186 187 188
void BackendPrivate::packageQueryFinished()
{
    Q_Q(Backend);

189
    QUuid uuid = QUuid(sender()->property("__Akabei_Query_Uuid").toString());
190 191 192
    if (!queryPackageFuturePool.contains(uuid)) {
        qWarning() << "No such UUID registered!";
        emit q->queryPackagesCompleted(uuid, QList<Package*>());
Dario Freddi's avatar
Dario Freddi committed
193
        sender()->deleteLater();
194 195 196 197
        return;
    }

    QList<Package*> retlist;
198
    // Create the result
199
    QFuture< QList< Package* > > const& future = queryPackageFuturePool[uuid]->future();
200 201 202 203
    for (QFuture< QList< Package* > >::const_iterator i = future.constBegin(); i != future.constEnd(); ++i) {
        retlist << *i;
    }

Dario Freddi's avatar
Dario Freddi committed
204
    sender()->deleteLater();
205 206 207 208 209 210 211
    emit q->queryPackagesCompleted(uuid, retlist);
}

void BackendPrivate::groupQueryFinished()
{
    Q_Q(Backend);

212
    QUuid uuid = QUuid(sender()->property("__Akabei_Query_Uuid").toString());
213 214
    if (!queryGroupFuturePool.contains(uuid)) {
        qWarning() << "No such UUID registered!";
Lukas Appelhans's avatar
Lukas Appelhans committed
215
        emit q->queryGroupsCompleted(uuid, QList<Group*>());
216 217 218 219
        return;
    }

    QList<Group*> retlist;
220
    // Create the result
221
    QFuture< QList< Group* > > const& future = queryGroupFuturePool[uuid]->future();
222 223 224 225
    for (QFuture< QList< Group* > >::const_iterator i = future.constBegin(); i != future.constEnd(); ++i) {
        retlist << *i;
    }

Lukas Appelhans's avatar
Lukas Appelhans committed
226
    emit q->queryGroupsCompleted(uuid, retlist);
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
void BackendPrivate::__k__lockGranted()
{
    Q_Q(Backend);
    setStatus(Backend::StatusInitializing);

    initializationWatcher = new QFutureWatcher< QHash< QString, Database* > >(this);
    QObject::connect(initializationWatcher, SIGNAL(finished()), q, SLOT(__k__initializationFinished()));

    QFuture< QHash< QString, Database* > > future = QtConcurrent::run(this, &BackendPrivate::performInitialization);
    initializationWatcher->setFuture(future);
}

void BackendPrivate::getLock()
{
    struct flock lockinfo;
    memset(&lockinfo, 0, sizeof(struct flock));

    lockinfo.l_type = F_WRLCK;
    lockinfo.l_whence = SEEK_SET;
    lockinfo.l_start = 0;
    lockinfo.l_len = 0;

    fcntl(localDatabaseFileHandler->handle(), F_SETLKW, &lockinfo);
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
///////////////////////////

GroupPool::GroupPool()
{
}

GroupPool::~GroupPool()
{
}

Group *GroupPool::group(const QString &name)
{
    if (!m_pool.contains(name)) {
        m_pool.insert(name, new Group(name));
    }

    return m_pool[name];
}

bool GroupPool::contains(const QString &name)
{
    return m_pool.contains(name);
}

278 279 280 281 282
///////////////////////////

class BackendHelper
{
public:
Daniele Cocca's avatar
Daniele Cocca committed
283 284 285 286 287 288
    BackendHelper()
      : q( 0 )
    {
    }

    virtual ~BackendHelper() {
289 290
        delete q;
    }
Daniele Cocca's avatar
Daniele Cocca committed
291 292

    Backend* q;
293 294 295 296
};

Q_GLOBAL_STATIC(BackendHelper, s_globalBackend)

Daniele Cocca's avatar
Daniele Cocca committed
297
Backend* Backend::instance()
298
{
299 300 301
    if (!s_globalBackend()->q) {
        new Backend;
    }
302 303 304 305 306 307 308 309 310 311

    return s_globalBackend()->q;
}

Backend::Backend(QObject* parent)
    : QObject(parent)
    , d_ptr(new BackendPrivate(this))
{
    Q_ASSERT(!s_globalBackend()->q);
    s_globalBackend()->q = this;
Dario Freddi's avatar
Dario Freddi committed
312 313 314
    qRegisterMetaType<QUuid>();
    qRegisterMetaType< QList< Akabei::Package* > >();
    qRegisterMetaType< QList< Akabei::Group* > >();
315

316
    // We need at least 2 threads in QThreadPool to make everything work correctly.
317
    if (QThreadPool::globalInstance()->maxThreadCount() < 2) {
318
        akabeiDebug() << "Set max thread count to 2";
319 320
        QThreadPool::globalInstance()->setMaxThreadCount(2);
    }
321 322
    
    qInstallMsgHandler(akabeiDebug);
323 324 325 326 327 328 329 330 331 332
}

Backend::~Backend()
{
}

void Backend::initialize()
{
    Q_D(Backend);

333 334 335 336 337 338 339 340 341 342 343 344
    d->localDatabaseFileHandler = new QFile(Akabei::Config::instance()->rootDir().absoluteFilePath("var/local/akabei.lck"));

    d->localDatabaseFileHandler->open(QFile::ReadWrite);

    struct flock lockinfo;
    memset(&lockinfo, 0, sizeof(struct flock));
    lockinfo.l_type = F_WRLCK;
    lockinfo.l_whence = SEEK_SET;
    lockinfo.l_start = 0;
    lockinfo.l_len = 0;

    if (fcntl(d->localDatabaseFileHandler->handle(), F_SETLK, &lockinfo) == -1) {
345
        akabeiDebug() << "No lock for us!";
346 347 348 349 350 351 352
        d->setStatus(StatusWaitingForLock);
        connect(&d->lockWatcher, SIGNAL(finished()), SLOT(__k__lockGranted()));
        QFuture<void> lockF = QtConcurrent::run(d, &BackendPrivate::getLock);
        d->lockWatcher.setFuture(lockF);
    } else {
        d->__k__lockGranted();
    }
353 354 355 356
}

QList< Database* > Backend::databases()
{
357 358
    Q_D(Backend);
    return d->databases;
359 360 361 362 363 364 365 366 367 368 369 370 371 372
}

Database* Backend::localDatabase()
{
    Q_D(Backend);
    return d->localDatabase;
}

Backend::Status Backend::status() const
{
    Q_D(const Backend);
    return d->status;
}

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
QUuid Backend::groups()
{
    QString sql = "SELECT * FROM groups";
    return queryGroups(sql);
}

QUuid Backend::packages()
{
    QString sql = "SELECT * FROM packages";
    return queryPackages(sql);
}

QUuid Backend::queryGroups(const QString& sql)
{
    Q_D(Backend);

    QUuid uuid = QUuid::createUuid();

    QList<Database*> allDbs;
    allDbs << d->localDatabase << d->databases;

Dario Freddi's avatar
Dario Freddi committed
394
    QFutureWatcher< QList< Group* > > *watcher = new QFutureWatcher< QList< Group* > >();
395
    watcher->setProperty("__Akabei_Query_Uuid", uuid.toString());
396 397 398 399 400
    connect(watcher, SIGNAL(finished()), d, SLOT(groupQueryFinished()));
    d->queryGroupFuturePool.insert(uuid, watcher);

    QFuture< QList< Group* > > future = QtConcurrent::mapped(allDbs, ConcurrentGroupQuery(sql));
    watcher->setFuture(future);
401 402

    return uuid;
403 404 405 406 407 408 409 410 411 412 413
}

QUuid Backend::queryPackages(const QString& sql)
{
    Q_D(Backend);

    QUuid uuid = QUuid::createUuid();

    QList<Database*> allDbs;
    allDbs << d->localDatabase << d->databases;

Daniele Cocca's avatar
Daniele Cocca committed
414
    QFutureWatcher< QList< Package* > >* watcher = new QFutureWatcher< QList< Package* > >();
415
    watcher->setProperty("__Akabei_Query_Uuid", uuid.toString());
416 417 418 419 420
    connect(watcher, SIGNAL(finished()), d, SLOT(packageQueryFinished()));
    d->queryPackageFuturePool.insert(uuid, watcher);

    QFuture< QList< Package* > > future = QtConcurrent::mapped(allDbs, ConcurrentPackageQuery(sql));
    watcher->setFuture(future);
421 422

    return uuid;
423 424 425 426
}

QUuid Backend::searchGroups(const QString& token)
{
427
    QString sql = "SELECT * FROM groups WHERE name LIKE \"%" + token + "%\" OR description LIKE \"%" + token + "%\"";
428 429
    return queryGroups(sql);
}
Daniele Cocca's avatar
Daniele Cocca committed
430

Lukas Appelhans's avatar
Lukas Appelhans committed
431 432
//TODO: Maybe abstract the query generation, because the same is used in database as well
QUuid Backend::searchPackages(const QString& token, SearchType type)
433
{
Lukas Appelhans's avatar
Lukas Appelhans committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    QString sql;
    switch (type) {
        case SearchNameLike:
            sql = "SELECT * FROM packages WHERE name LIKE \"%" + token + "%\"";
            break;
        case SearchNameEqual:
            sql = "SELECT * FROM packages WHERE name=\"" + token + "\"";
            break;
        case SearchDescriptionLike:
            sql = "SELECT * FROM packages WHERE description LIKE \"%" + token + "%\"";
            break;
        case SearchDescriptionEqual:
            sql = "SELECT * FROM packages WHERE description=\"" + token + "\"";
            break;
        case SearchNameAndDescriptionLike:
            sql = "SELECT * FROM packages WHERE name LIKE \"%" + token + "%\" OR description LIKE \"%" + token + "%\"";
            break;
        case SearchNameAndDescriptionEqual:
            sql = "SELECT * FROM PACKAGES WHERE name=\"" + token + "\" OR description=\"" + token + "\"";
            break;
    }
455 456 457
    return queryPackages(sql);
}

Lukas Appelhans's avatar
Lukas Appelhans committed
458
QUuid Backend::searchPackages(const QStringList &pkgs, SearchType type)
Lisa's avatar
Lisa committed
459 460
{
    QString sql = "SELECT * FROM packages WHERE ";
461

Lukas Appelhans's avatar
Lukas Appelhans committed
462
    for (QStringList::const_iterator it = pkgs.begin(); it < pkgs.end(); it++) {
Lukas Appelhans's avatar
Lukas Appelhans committed
463 464 465 466 467 468 469 470 471 472 473
        switch (type) {
            case SearchNameEqual:
                sql += "name=\"" + (*it) + "\" ";
                break;
            case SearchNameLike:
                sql += "name LIKE \"%" + (*it) + "%\" ";
                break;
            case SearchDescriptionEqual:
                sql += "description=\"" + (*it) + "\" ";
                break;
            case SearchDescriptionLike:
Lisa's avatar
Lisa committed
474
                sql += "description LIKE \"%" + (*it) + "%\" ";
Lukas Appelhans's avatar
Lukas Appelhans committed
475 476 477 478 479 480 481
                break;
            case SearchNameAndDescriptionEqual:
                sql += "name=\"" + (*it) + "\" OR description=\"" + (*it) + "\" ";
                break;
            case SearchNameAndDescriptionLike:
                sql += "name LIKE \"%" + (*it) + "%\" OR description LIKE \"%" + (*it) + "%\" ";
        }
482

Lukas Appelhans's avatar
Lukas Appelhans committed
483
        if ((it + 1) != pkgs.end()) {
Lisa's avatar
Lisa committed
484 485 486
            sql += "OR ";
        }
    }
487

Lisa's avatar
Lisa committed
488 489 490
    return queryPackages(sql);
}

491 492 493 494 495 496
OperationRunner* Backend::operationRunner()
{
    Q_D(Backend);
    return d->runner;
}

497 498 499 500 501 502 503
Package* Backend::loadPackageFromFile(const QString& path)
{
    Q_D(Backend);

    if (!QFile::exists(path)) {
        return 0;
    }
504

Daniele Cocca's avatar
Daniele Cocca committed
505
    Package* retpackage = new Package;
506 507
    retpackage->d_func()->hasScriptlet = false;
    retpackage->d_func()->hasHooks = false;
508
    retpackage->d_func()->pathToArchive = path;
509

510
    try {
511
        ArchiveHandler pkg(path);
512 513 514 515
        /* If full is false, only read through the archive until we find our needed
         * metadata. If it is true, read through the entire archive, which serves
         * as a verfication of integrity and allows us to create the filelist. */

516
        foreach (QString const& line, pkg.readTextFile(".PKGINFO").split('\n')) {
517 518 519
            if (!line.contains('=') || line.startsWith('#')) {
                // Skip this line, not interesting
                continue;
520
            }
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

            // Separate the two strings
            QStringList splitted = line.split('=');
            QString key = splitted.first();
            // There might be an equal, so
            splitted.removeAt(0);
            QString value = splitted.join(QChar('='));

            // Just remove all spaces ignorantly here
            key = key.remove(' ');
            // Recheck if it's commented over
            if (key.startsWith('#')) {
                // Pass by
            }

            // Strip whitespaces here instead
Lisa's avatar
Lisa committed
537
            value = value.simplified();
538 539 540 541 542 543 544 545 546 547 548 549 550

            // Ok, now let's analyze
            if (key == "pkgname") {
                retpackage->d_func()->name = value;
            } else if (key == "pkgver") {
                retpackage->d_func()->version = value.toUtf8();
            } else if (key == "pkgdesc") {
                retpackage->d_func()->desc = value;
            } else if (key == "group") {
                retpackage->d_func()->groups << d->groupPool->group(value);
            } else if (key == "url") {
                retpackage->d_func()->url = QUrl(value);
            } else if (key == "license") {
551
                retpackage->d_func()->licenses << value;
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
            } else if (key == "builddate") {
                retpackage->d_func()->buildDate = QDateTime::fromTime_t(value.toUInt());
            } else if (key == "packager") {
                retpackage->d_func()->packager = value;
            } else if (key == "arch") {
                retpackage->d_func()->arch = value;
            } else if (key == "size") {
                retpackage->d_func()->size = value.toInt();
            } else if (key == "depend") {
                retpackage->d_func()->deps << value;
            } else if (key == "optdepend") {
                retpackage->d_func()->optdepends << value;
            } else if (key == "conflict") {
                retpackage->d_func()->conflicts << value;
            } else if (key == "replaces") {
                retpackage->d_func()->replaces << value;
            } else if (key == "provides") {
                retpackage->d_func()->providers << value;
            } else if (key == "hook") {
                retpackage->d_func()->hooks << value;
            } else if (key == "backup") {
573
                retpackage->d_func()->backup.insert(value, pkg.md5(value));
574 575
            } else if (key == "makepkgopt") {
    //                     retpackage->d_func()->arch = value;
Lukas Appelhans's avatar
Typo  
Lukas Appelhans committed
576
            } else if (key == "screenshot") {
577 578 579 580 581 582
                retpackage->d_func()->screenshot = QUrl(value);
            } else if (key == "mimetype") {
                retpackage->d_func()->mimetypes << value;
            } else if (key == "hook") {
                retpackage->d_func()->hooks << value;
                retpackage->d_func()->hasHooks = true;
583 584
            } else if (key == "epoch") {
                retpackage->d_func()->version.d->epoch = value.toInt();
585 586 587 588 589 590 591 592 593 594 595 596
            } else if (key == "gitfolder") {
                retpackage->d_func()->gitFolder = value;
            } else if (key == "gitrepository") {
                retpackage->d_func()->gitRepo = value;
            } else if (key == "gitbranch") {
                retpackage->d_func()->gitBranch = value;
            } else if (key == "gitrepo") { //This is legacy support
                QStringList split = value.split("-");
                if (!split.isEmpty()) {
                    retpackage->d_func()->gitRepo = split.takeFirst();
                    retpackage->d_func()->gitBranch = split.isEmpty() ? "master" : split.first();
                }
597 598
            }
        }
599

600 601
        if (pkg.getEntries().contains(".INSTALL")) {
            retpackage->d_func()->scriptlet = pkg.readTextFile(".INSTALL");
602
            retpackage->d_func()->hasScriptlet = true;
603
        }
604

605 606 607 608 609 610
        retpackage->d_func()->files = pkg.getEntries();
        retpackage->d_func()->isize = 0;
        foreach (QString const& entry, retpackage->d_func()->files) {
            retpackage->d_func()->isize += pkg.getEntrySize(entry);
        }

611
    } catch (ArchiveException& e) {
612
        akabeiDebug() << "Error during access in archive: " << e.what();
613 614 615
        delete retpackage;
        return 0;
    }
616

617 618 619 620 621
    if (retpackage->name().isEmpty()) {
        delete retpackage;
        return 0;
    }

622
    // Now add md5sum and filename, of course
Dario Freddi's avatar
Dario Freddi committed
623
    retpackage->d_func()->filename = path.split('/').last();
624
    retpackage->d_func()->md5sum = Helpers::md5sumOfFile(path);
625 626 627

    // And size
    QFileInfo finfo(path);
628
    retpackage->d_func()->size = finfo.size();
629 630

    // Fill some fields
631 632
    retpackage->d_func()->installDate = QDateTime();
    retpackage->d_func()->reason = Package::NoReason;
633 634

    // We already computed md5 and validation, so set em up
635 636 637
    retpackage->d_func()->_p_md5checked = true;
    retpackage->d_func()->_p_validated = true;

638 639 640
    return retpackage;
}

641 642 643 644 645
Delta* Backend::loadDeltaFromFile(const QString& path)
{
    if (!QFile::exists(path)) {
        return 0;
    }
646

647
    ArchiveHandler delta(path);
648

Daniele Cocca's avatar
Daniele Cocca committed
649
    Delta* retdelta = new Delta(QString(), QByteArray(), QByteArray());
650
    retdelta->d_func()->pathToDelta = path;
651

652 653
    try {
        /* It can be only our delta */
654
        foreach (QString const& entry, delta.getEntries()) {
655
            if (entry != ".DELTAINFO" && entry != "." && entry != path.split('/').last().remove(".tar.xz")) {
656 657 658 659
                delete retdelta;
                return 0;
            }
        }
660

661 662 663
       /* If full is false, only read through the archive until we find our needed
        * metadata. If it is true, read through the entire archive, which serves
        * as a verfication of integrity and allows us to create the filelist. */
664
        foreach (QString const& line, delta.readTextFile(".DELTAINFO").split('\n')) {
665 666 667 668
            if (!line.contains('=') || line.startsWith('#')) {
                // Skip this line, not interesting
                continue;
            }
669

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            // Separate the two strings
            QStringList splitted = line.split('=');
            QString key = splitted.first();
            // There might be an equal, so
            splitted.removeAt(0);
            QString value = splitted.join(QChar('='));

            // Just remove all spaces ignorantly here
            key = key.remove(' ');
            // Recheck if it's commented over
            if (key.startsWith('#')) {
                // Pass by
            }

            // Strip whitespaces here instead
Lisa's avatar
Lisa committed
685
            value = value.simplified();
686 687 688 689 690 691 692 693 694 695

            // Ok, now let's analyze
            if (key == "pkgname") {
                retdelta->d_func()->name = value;
            } else if (key == "verfrom") {
                retdelta->d_func()->vFrom = value.toUtf8();
            } else if (key == "verto") {
                retdelta->d_func()->vTo = value.toUtf8();
            }
        }
Daniele Cocca's avatar
Daniele Cocca committed
696
    } catch (ArchiveException const& e) {
697
        akabeiDebug() << "Error during access to archive: " << e.what();
698 699
        delete retdelta;
        return 0;
700 701
    }

702 703 704 705 706
    if (retdelta->targetName().isEmpty()) {
        delete retdelta;
        return 0;
    }

707
    // Now add md5sum and filename, of course
708 709
    retdelta->d_func()->filename = path.split('/').last();
    retdelta->d_func()->md5sum = Helpers::md5sumOfFile(path);
710 711

    // We already computed md5 and validation, so set em up
712 713 714 715 716 717
    retdelta->d_func()->_p_md5checked = true;
    retdelta->d_func()->_p_validated = true;

    return retdelta;
}

718 719 720
Group* Backend::loadGroupFromFile(const QString &path)
{
    Q_D(Backend);
721

Daniele Cocca's avatar
Daniele Cocca committed
722 723 724 725
    Group* group( 0 );
    QFile file( path );

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
726
        return group;
Daniele Cocca's avatar
Daniele Cocca committed
727
    }
728

Daniele Cocca's avatar
Daniele Cocca committed
729
    QTextStream in( &file );
730
    while (!in.atEnd()) {
Daniele Cocca's avatar
Daniele Cocca committed
731 732
        QStringList split( in.readLine().split('=') );

733
        if (split.isEmpty()) {
734
            continue;
735
        }
Daniele Cocca's avatar
Daniele Cocca committed
736

Lukas Appelhans's avatar
Lukas Appelhans committed
737
        if (split.first() == "Name") {
738
            group = d->groupPool->group(split.last());
Daniele Cocca's avatar
Daniele Cocca committed
739
        } else if (group != 0 && split.first() == "Description") {
740
            group->d_ptr->desc = split.last();
Daniele Cocca's avatar
Daniele Cocca committed
741
        } else if (group != 0 && split.first() == "Iconname") {
742 743 744
            group->d_ptr->icon = split.last();
        }
    }
745
    return group;
746 747
}

Lukas Appelhans's avatar
Lukas Appelhans committed
748 749
Hook* Backend::loadHookFromFile(const QString& path, QList<Package*> pkgs)
{
750
    QFile file(path);
Lukas Appelhans's avatar
Lukas Appelhans committed
751

752 753
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return 0;
Lukas Appelhans's avatar
Lukas Appelhans committed
754
    }
755 756 757 758 759

    QString name( path.split('/').last().remove(".hook") );
    QTextStream in( &file );

    return new Hook(name, in.readAll(), pkgs);
Lukas Appelhans's avatar
Lukas Appelhans committed
760 761
}

762 763
Database* Backend::loadDatabaseFromFile(const QString& path)
{
Daniele Cocca's avatar
Daniele Cocca committed
764
    if (!QFile::exists(path)) {
765 766 767 768 769 770 771 772
        qWarning() << "The databases file does not exist:" << path;
        return 0;
    }

    Database* database = new Database(path);
    if (!database->isValid()) {
        qWarning() << "Invalid database:" << path;
        delete database;
773
        return 0;
Daniele Cocca's avatar
Daniele Cocca committed
774 775
    }

776
    return database;
777 778
}

779 780 781
}

#include "akabeibackend.moc"