jobs.cpp 22.2 KB
Newer Older
1 2
/*
 * Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net>
3
 * Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no>
4
 * Copyright (c) 2009-2012 Raphael Kubo da Costa <rakuco@FreeBSD.org>
5
 * Copyright (c) 2016 Vladyslav Batyrenko <mvlabat@gmail.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
28

29
#include "jobs.h"
30
#include "archiveentry.h"
31
#include "ark_debug.h"
32

33
#include <QDir>
34
#include <QDirIterator>
35
#include <QFileInfo>
36
#include <QRegularExpression>
37
#include <QThread>
38
#include <QTimer>
Elvis Angelaccio's avatar
Elvis Angelaccio committed
39
#include <QUrl>
40

Elvis Angelaccio's avatar
Elvis Angelaccio committed
41
#include <KIO/RenameDialog>
42
#include <KLocalizedString>
43

44 45
namespace Kerfuffle
{
46

47 48 49
class Job::Private : public QThread
{
public:
50 51 52 53 54 55
    Private(Job *job, QObject *parent = 0)
        : QThread(parent)
        , q(job)
    {
    }

56
    virtual void run() Q_DECL_OVERRIDE;
57

58
private:
59 60 61 62 63
    Job *q;
};

void Job::Private::run()
{
64
    q->doWork();
65 66
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
67
Job::Job(Archive *archive, ReadOnlyArchiveInterface *interface)
Elvis Angelaccio's avatar
Elvis Angelaccio committed
68
    : KJob()
Elvis Angelaccio's avatar
Elvis Angelaccio committed
69
    , m_archive(archive)
70
    , m_archiveInterface(interface)
71
    , d(new Private(this))
72 73 74 75
{
    setCapabilities(KJob::Killable);
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
76 77 78 79 80 81 82 83
Job::Job(Archive *archive)
    : Job(archive, Q_NULLPTR)
{}

Job::Job(ReadOnlyArchiveInterface *interface)
    : Job(Q_NULLPTR, interface)
{}

84 85
Job::~Job()
{
86 87 88
    qDeleteAll(m_archiveEntries);
    m_archiveEntries.clear();

89 90
    if (d->isRunning()) {
        d->wait();
91 92
    }

93
    delete d;
94
}
95

96 97
ReadOnlyArchiveInterface *Job::archiveInterface()
{
Elvis Angelaccio's avatar
Elvis Angelaccio committed
98 99 100 101 102 103
    // Use the archive interface.
    if (archive()) {
        return archive()->interface();
    }

    // Use the interface passed to this job (e.g. JSONArchiveInterface in jobstest.cpp).
104 105 106
    return m_archiveInterface;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
Archive *Job::archive() const
{
    return m_archive;
}

QString Job::errorString() const
{
    if (!errorText().isEmpty()) {
        return errorText();
    }

    if (archive()) {
        if (archive()->error() == NoPlugin) {
            return i18n("No suitable plugin found. Ark does not seem to support this file type.");
        }

        if (archive()->error() == FailedPlugin) {
            return i18n("Failed to load a suitable plugin. Make sure any executables needed to handle the archive type are installed.");
        }
    }

    return QString();
}

131 132
void Job::start()
{
133
    jobTimer.start();
134

Elvis Angelaccio's avatar
Elvis Angelaccio committed
135 136 137 138 139 140 141 142
    // We have an archive but it's not valid, nothing to do.
    if (archive() && !archive()->isValid()) {
        QTimer::singleShot(0, this, [=]() {
            onFinished(false);
        });
        return;
    }

143
    if (archiveInterface()->waitForFinishedSignal()) {
144 145 146 147 148 149
        // CLI-based interfaces run a QProcess, no need to use threads.
        QTimer::singleShot(0, this, &Job::doWork);
    } else {
        // Run the job in another thread.
        d->start();
    }
150 151
}

152 153
void Job::connectToArchiveInterfaceSignals()
{
Laurent Montel's avatar
Laurent Montel committed
154 155 156 157 158 159
    connect(archiveInterface(), &ReadOnlyArchiveInterface::cancelled, this, &Job::onCancelled);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::error, this, &Job::onError);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::entry, this, &Job::onEntry);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::entryRemoved, this, &Job::onEntryRemoved);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::progress, this, &Job::onProgress);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::info, this, &Job::onInfo);
160
    connect(archiveInterface(), &ReadOnlyArchiveInterface::finished, this, &Job::onFinished);
Laurent Montel's avatar
Laurent Montel committed
161
    connect(archiveInterface(), &ReadOnlyArchiveInterface::userQuery, this, &Job::onUserQuery);
162 163
}

164 165
void Job::onCancelled()
{
166
    qCDebug(ARK) << "Cancelled emitted";
167 168 169
    setError(KJob::KilledJobError);
}

170 171
void Job::onError(const QString & message, const QString & details)
{
172
    Q_UNUSED(details)
173

174
    qCDebug(ARK) << "Error emitted:" << message;
175
    setError(KJob::UserDefinedError);
176 177 178
    setErrorText(message);
}

179
void Job::onEntry(Archive::Entry *entry)
180
{
181
    emit newEntry(entry);
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
}

void Job::onProgress(double value)
{
    setPercent(static_cast<unsigned long>(100.0*value));
}

void Job::onInfo(const QString& info)
{
    emit infoMessage(this, info);
}

void Job::onEntryRemoved(const QString & path)
{
    emit entryRemoved(path);
}

void Job::onFinished(bool result)
{
201
    qCDebug(ARK) << "Job finished, result:" << result << ", time:" << jobTimer.elapsed() << "ms";
202

Elvis Angelaccio's avatar
Elvis Angelaccio committed
203 204 205 206
    if (archive() && !archive()->isValid()) {
        setError(KJob::UserDefinedError);
    }

207 208 209 210 211 212 213 214 215 216
    emitResult();
}

void Job::onUserQuery(Query *query)
{
    emit userQuery(query);
}

bool Job::doKill()
{
217 218 219 220 221
    if (d->isRunning()) {
        d->requestInterruption();
        d->wait();
    }

222
    bool ret = archiveInterface()->doKill();
223
    if (!ret) {
224
        qCWarning(ARK) << "Killing does not seem to be supported here.";
225
    }
226 227 228
    return ret;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
229 230
LoadJob::LoadJob(Archive *archive, ReadOnlyArchiveInterface *interface)
    : Job(archive, interface)
231 232 233
    , m_isSingleFolderArchive(true)
    , m_isPasswordProtected(false)
    , m_extractedFilesSize(0)
234 235
    , m_dirCount(0)
    , m_filesCount(0)
236
{
Elvis Angelaccio's avatar
Elvis Angelaccio committed
237 238
    qCDebug(ARK) << "LoadJob started";
    connect(this, &LoadJob::newEntry, this, &LoadJob::onNewEntry);
239 240
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
241 242 243 244 245 246 247 248 249
LoadJob::LoadJob(Archive *archive)
    : LoadJob(archive, Q_NULLPTR)
{}

LoadJob::LoadJob(ReadOnlyArchiveInterface *interface)
    : LoadJob(Q_NULLPTR, interface)
{}

void LoadJob::doWork()
250
{
251
    emit description(this, i18n("Loading archive"));
252
    connectToArchiveInterfaceSignals();
Elvis Angelaccio's avatar
Elvis Angelaccio committed
253

254
    bool ret = archiveInterface()->list();
255

256
    if (!archiveInterface()->waitForFinishedSignal()) {
257
        onFinished(ret);
258
    }
259 260
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
void LoadJob::onFinished(bool result)
{
    if (archive()) {
        archive()->setProperty("unpackedSize", extractedFilesSize());
        archive()->setProperty("isSingleFolder", isSingleFolderArchive());
        const auto name = subfolderName().isEmpty() ? archive()->completeBaseName() : subfolderName();
        archive()->setProperty("subfolderName", name);
        if (isPasswordProtected()) {
            archive()->setProperty("encryptionType",  archive()->password().isEmpty() ? Archive::Encrypted : Archive::HeaderEncrypted);
        }
    }

    Job::onFinished(result);
}

qlonglong LoadJob::extractedFilesSize() const
277 278 279 280
{
    return m_extractedFilesSize;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
281
bool LoadJob::isPasswordProtected() const
282 283 284 285
{
    return m_isPasswordProtected;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
286
bool LoadJob::isSingleFolderArchive() const
287
{
288 289 290 291
    if (m_filesCount == 1 && m_dirCount == 0) {
        return false;
    }

292 293 294
    return m_isSingleFolderArchive;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
295
void LoadJob::onNewEntry(const Archive::Entry *entry)
296
{
297 298
    m_extractedFilesSize += entry->property("size").toLongLong();
    m_isPasswordProtected |= entry->property("isPasswordProtected").toBool();
299

300
    if (entry->isDir()) {
301 302 303 304 305
        m_dirCount++;
    } else {
        m_filesCount++;
    }

306
    if (m_isSingleFolderArchive) {
307
        // RPM filenames have the ./ prefix, and "." would be detected as the subfolder name, so we remove it.
308
        const QString fullPath = entry->fullPath().replace(QRegularExpression(QStringLiteral("^\\./")), QString());
309
        const QString basePath = fullPath.split(QLatin1Char('/')).at(0);
310

311 312 313
        if (m_basePath.isEmpty()) {
            m_basePath = basePath;
            m_subfolderName = basePath;
314
        } else {
315 316 317 318
            if (m_basePath != basePath) {
                m_isSingleFolderArchive = false;
                m_subfolderName.clear();
            }
319 320 321 322
        }
    }
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
323
QString LoadJob::subfolderName() const
324
{
325 326 327 328
    if (!isSingleFolderArchive()) {
        return QString();
    }

329 330 331
    return m_subfolderName;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345
BatchExtractJob::BatchExtractJob(LoadJob *loadJob, const QString &destination, bool autoSubfolder, bool preservePaths)
    : Job(loadJob->archive())
    , m_loadJob(loadJob)
    , m_destination(destination)
    , m_autoSubfolder(autoSubfolder)
    , m_preservePaths(preservePaths)
{
    qCDebug(ARK) << "BatchExtractJob created";
}

void BatchExtractJob::doWork()
{
    connect(m_loadJob, &KJob::result, this, &BatchExtractJob::slotLoadingFinished);

346
    // Forward LoadJob's signals.
Elvis Angelaccio's avatar
Elvis Angelaccio committed
347 348 349 350 351 352 353 354
    connect(m_loadJob, &Kerfuffle::Job::newEntry, this, &BatchExtractJob::newEntry);
    connect(m_loadJob, &Kerfuffle::Job::userQuery, this, &BatchExtractJob::userQuery);
    m_loadJob->start();
}

void BatchExtractJob::slotLoadingFinished(KJob *job)
{
    if (job->error()) {
355 356 357
        // Forward errors as well.
        onError(job->errorString(), QString());
        onFinished(false);
Elvis Angelaccio's avatar
Elvis Angelaccio committed
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
        return;
    }

    // Now we can start extraction.
    setupDestination();

    Kerfuffle::ExtractionOptions options;
    options[QStringLiteral("PreservePaths")] = m_preservePaths;

    auto extractJob = archive()->extractFiles({}, m_destination, options);
    if (extractJob) {
        connect(extractJob, &KJob::result, this, &BatchExtractJob::emitResult);
        connect(extractJob, &Kerfuffle::Job::userQuery, this, &BatchExtractJob::userQuery);
        extractJob->start();
    } else {
        emitResult();
    }
}

void BatchExtractJob::setupDestination()
{
    const bool isSingleFolderRPM = (archive()->isSingleFolder() &&
                                   (archive()->mimeType().name() == QLatin1String("application/x-rpm")));

    if (m_autoSubfolder && (!archive()->isSingleFolder() || isSingleFolderRPM)) {
        const QDir d(m_destination);
        QString subfolderName = archive()->subfolderName();

        // Special case for single folder RPM archives.
        // We don't want the autodetected folder to have a meaningless "usr" name.
        if (isSingleFolderRPM && subfolderName == QStringLiteral("usr")) {
            qCDebug(ARK) << "Detected single folder RPM archive. Using archive basename as subfolder name";
            subfolderName = QFileInfo(archive()->fileName()).completeBaseName();
        }

        if (d.exists(subfolderName)) {
            subfolderName = KIO::suggestName(QUrl::fromUserInput(m_destination, QString(), QUrl::AssumeLocalFile), subfolderName);
        }

        d.mkdir(subfolderName);

        m_destination += QLatin1Char( '/' ) + subfolderName;
    }
}

CreateJob::CreateJob(Archive *archive, const QList<Archive::Entry *> &entries, const CompressionOptions &options)
    : Job(archive)
    , m_entries(entries)
    , m_options(options)
{
    qCDebug(ARK) << "CreateJob created";
}

void CreateJob::enableEncryption(const QString &password, bool encryptHeader)
{
    archive()->encrypt(password, encryptHeader);
}

void CreateJob::setMultiVolume(bool isMultiVolume)
{
    archive()->setMultiVolume(isMultiVolume);
}

void CreateJob::doWork()
{
    auto addJob = archive()->addFiles(m_entries, new Archive::Entry(this), m_options);

    if (addJob) {
        connect(addJob, &KJob::result, this, &CreateJob::emitResult);
        addJob->start();
    } else {
        emitResult();
    }
}

433
ExtractJob::ExtractJob(const QList<Archive::Entry*> &entries, const QString &destinationDir, const ExtractionOptions &options, ReadOnlyArchiveInterface *interface)
Elvis Angelaccio's avatar
Elvis Angelaccio committed
434
    : Job(interface)
435
    , m_entries(entries)
436 437
    , m_destinationDir(destinationDir)
    , m_options(options)
438
{
439
    qCDebug(ARK) << "ExtractJob created";
440
    setDefaultOptions();
441 442 443 444 445
}

void ExtractJob::doWork()
{
    QString desc;
446
    if (m_entries.count() == 0) {
447 448
        desc = i18n("Extracting all files");
    } else {
449
        desc = i18np("Extracting one file", "Extracting %1 files", m_entries.count());
450 451 452
    }
    emit description(this, desc);

453 454 455 456 457 458 459
    QFileInfo destDirInfo(m_destinationDir);
    if (destDirInfo.isDir() && (!destDirInfo.isWritable() || !destDirInfo.isExecutable())) {
        onError(xi18n("Could not write to destination <filename>%1</filename>.<nl/>Check whether you have sufficient permissions.", m_destinationDir), QString());
        onFinished(false);
        return;
    }

460
    connectToArchiveInterfaceSignals();
461

462
    qCDebug(ARK) << "Starting extraction with" << m_entries.count() << "selected files."
463
             << m_entries
464 465
             << "Destination dir:" << m_destinationDir
             << "Options:" << m_options;
466

467
    bool ret = archiveInterface()->extractFiles(m_entries, m_destinationDir, m_options);
468

469
    if (!archiveInterface()->waitForFinishedSignal()) {
470
        onFinished(ret);
471
    }
472 473
}

474
void ExtractJob::setDefaultOptions()
475
{
476 477
    ExtractionOptions defaultOptions;

478
    defaultOptions[QStringLiteral("PreservePaths")] = false;
479 480 481 482 483 484

    ExtractionOptions::const_iterator it = defaultOptions.constBegin();
    for (; it != defaultOptions.constEnd(); ++it) {
        if (!m_options.contains(it.key())) {
            m_options[it.key()] = it.value();
        }
485 486 487
    }
}

488 489 490 491 492
QString ExtractJob::destinationDirectory() const
{
    return m_destinationDir;
}

493 494 495 496 497
ExtractionOptions ExtractJob::extractionOptions() const
{
    return m_options;
}

498
TempExtractJob::TempExtractJob(Archive::Entry *entry, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
499
    : Job(interface)
500
    , m_entry(entry)
501 502
    , m_passwordProtectedHint(passwordProtectedHint)
{
503
    m_tmpExtractDir = new QTemporaryDir();
504 505 506 507
}

QString TempExtractJob::validatedFilePath() const
{
508
    QString path = extractionDir() + QLatin1Char('/') + m_entry->fullPath();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    // Make sure a maliciously crafted archive with parent folders named ".." do
    // not cause the previewed file path to be located outside the temporary
    // directory, resulting in a directory traversal issue.
    path.remove(QStringLiteral("../"));

    return path;
}

ExtractionOptions TempExtractJob::extractionOptions() const
{
    ExtractionOptions options;
    options[QStringLiteral("PreservePaths")] = true;

    if (m_passwordProtectedHint) {
        options[QStringLiteral("PasswordProtectedHint")] = true;
    }

    return options;
}

530 531 532 533 534
QTemporaryDir *TempExtractJob::tempDir() const
{
    return m_tmpExtractDir;
}

535 536 537 538 539 540
void TempExtractJob::doWork()
{
    emit description(this, i18n("Extracting one file"));

    connectToArchiveInterfaceSignals();

541
    qCDebug(ARK) << "Extracting:" << m_entry;
542

543
    bool ret = archiveInterface()->extractFiles({m_entry}, extractionDir(), extractionOptions());
544 545 546 547 548 549

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

550
QString TempExtractJob::extractionDir() const
551
{
552
    return m_tmpExtractDir->path();
553 554
}

555 556
PreviewJob::PreviewJob(Archive::Entry *entry, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : TempExtractJob(entry, passwordProtectedHint, interface)
557
{
558
    qCDebug(ARK) << "PreviewJob started";
559 560
}

561 562
OpenJob::OpenJob(Archive::Entry *entry, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : TempExtractJob(entry, passwordProtectedHint, interface)
563 564 565 566
{
    qCDebug(ARK) << "OpenJob started";
}

567 568
OpenWithJob::OpenWithJob(Archive::Entry *entry, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : OpenJob(entry, passwordProtectedHint, interface)
569 570 571 572
{
    qCDebug(ARK) << "OpenWithJob started";
}

573
AddJob::AddJob(const QList<Archive::Entry*> &entries, const Archive::Entry *destination, const CompressionOptions& options , ReadWriteArchiveInterface *interface)
Elvis Angelaccio's avatar
Elvis Angelaccio committed
574
    : Job(interface)
575
    , m_entries(entries)
576
    , m_destination(destination)
577
    , m_options(options)
578
{
579
    qCDebug(ARK) << "AddJob started";
580 581 582 583
}

void AddJob::doWork()
{
584
    // Set current dir.
585 586 587 588 589 590 591 592
    const QString globalWorkDir = m_options.value(QStringLiteral("GlobalWorkDir")).toString();
    const QDir workDir = globalWorkDir.isEmpty() ? QDir::current() : QDir(globalWorkDir);
    if (!globalWorkDir.isEmpty()) {
        qCDebug(ARK) << "GlobalWorkDir is set, changing dir to " << globalWorkDir;
        m_oldWorkingDir = QDir::currentPath();
        QDir::setCurrent(globalWorkDir);
    }

593 594 595 596
    // Count total number of entries to be added.
    qulonglong totalCount = 0;
    QElapsedTimer timer;
    timer.start();
597
    foreach (const Archive::Entry* entry, m_entries) {
598
        totalCount++;
599
        if (QFileInfo(entry->fullPath()).isDir()) {
600
            QDirIterator it(entry->fullPath(), QDir::AllEntries | QDir::Readable | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
            while (it.hasNext()) {
                it.next();
                totalCount++;
            }
        }
    }
    qCDebug(ARK) << "Counted" << totalCount << "entries in" << timer.elapsed() << "ms";

    m_options[QStringLiteral("NumberOfEntries")] = totalCount;

    qCDebug(ARK) << "AddJob: going to add" << totalCount << "entries";
    emit description(this, i18np("Adding a file", "Adding %1 files", totalCount));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

619
    // The file paths must be relative to GlobalWorkDir.
620
    foreach (Archive::Entry *entry, m_entries) {
621 622
        // #191821: workDir must be used instead of QDir::current()
        //          so that symlinks aren't resolved automatically
623
        const QString &fullPath = entry->fullPath();
624
        QString relativePath = workDir.relativeFilePath(fullPath);
625

626
        if (fullPath.endsWith(QLatin1Char('/'))) {
627 628 629
            relativePath += QLatin1Char('/');
        }

630
        entry->setFullPath(relativePath);
631 632
    }

633
    connectToArchiveInterfaceSignals();
634
    bool ret = m_writeInterface->addFiles(m_entries, m_destination, m_options);
635

636
    if (!archiveInterface()->waitForFinishedSignal()) {
637
        onFinished(ret);
638
    }
639 640
}

641 642 643 644 645 646 647 648 649
void AddJob::onFinished(bool result)
{
    if (!m_oldWorkingDir.isEmpty()) {
        QDir::setCurrent(m_oldWorkingDir);
    }

    Job::onFinished(result);
}

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
MoveJob::MoveJob(const QList<Archive::Entry*> &entries, Archive::Entry *destination, const CompressionOptions& options , ReadWriteArchiveInterface *interface)
    : Job(interface)
    , m_finishedSignalsCount(0)
    , m_entries(entries)
    , m_destination(destination)
    , m_options(options)
{
    qCDebug(ARK) << "MoveJob started";
}

void MoveJob::doWork()
{
    qCDebug(ARK) << "MoveJob: going to move" << m_entries.count() << "file(s)";

    emit description(this, i18np("Moving a file", "Moving %1 files", m_entries.count()));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

    connectToArchiveInterfaceSignals();
    bool ret = m_writeInterface->moveFiles(m_entries, m_destination, m_options);

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

void MoveJob::onFinished(bool result)
{
    m_finishedSignalsCount++;
    if (m_finishedSignalsCount == archiveInterface()->moveRequiredSignals()) {
        Job::onFinished(result);
    }
}

CopyJob::CopyJob(const QList<Archive::Entry*> &entries, Archive::Entry *destination, const CompressionOptions &options, ReadWriteArchiveInterface *interface)
    : Job(interface)
    , m_finishedSignalsCount(0)
    , m_entries(entries)
    , m_destination(destination)
    , m_options(options)
{
    qCDebug(ARK) << "CopyJob started";
}

void CopyJob::doWork()
{
    qCDebug(ARK) << "CopyJob: going to copy" << m_entries.count() << "file(s)";

    emit description(this, i18np("Copying a file", "Copying %1 files", m_entries.count()));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

    connectToArchiveInterfaceSignals();
    bool ret = m_writeInterface->copyFiles(m_entries, m_destination, m_options);

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

void CopyJob::onFinished(bool result)
{
    m_finishedSignalsCount++;
    if (m_finishedSignalsCount == archiveInterface()->copyRequiredSignals()) {
        Job::onFinished(result);
    }
}

DeleteJob::DeleteJob(const QList<Archive::Entry*> &entries, ReadWriteArchiveInterface *interface)
Elvis Angelaccio's avatar
Elvis Angelaccio committed
725
    : Job(interface)
726
    , m_entries(entries)
727 728 729 730 731
{
}

void DeleteJob::doWork()
{
732
    emit description(this, i18np("Deleting a file from the archive", "Deleting %1 files", m_entries.count()));
733 734

    ReadWriteArchiveInterface *m_writeInterface =
735
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());
736 737 738

    Q_ASSERT(m_writeInterface);

739
    connectToArchiveInterfaceSignals();
740
    bool ret = m_writeInterface->deleteFiles(m_entries);
741

742
    if (!archiveInterface()->waitForFinishedSignal()) {
743
        onFinished(ret);
744
    }
745
}
746

Elvis Angelaccio's avatar
Elvis Angelaccio committed
747 748
CommentJob::CommentJob(const QString& comment, ReadWriteArchiveInterface *interface)
    : Job(interface)
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    , m_comment(comment)
{
}

void CommentJob::doWork()
{
    emit description(this, i18n("Adding comment"));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

    connectToArchiveInterfaceSignals();
    bool ret = m_writeInterface->addComment(m_comment);

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
770 771
TestJob::TestJob(ReadOnlyArchiveInterface *interface)
    : Job(interface)
Ragnar Thomsen's avatar
Ragnar Thomsen committed
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
{
    m_testSuccess = false;
}

void TestJob::doWork()
{
    qCDebug(ARK) << "TestJob started";

    emit description(this, i18n("Testing archive"));
    connectToArchiveInterfaceSignals();
    connect(archiveInterface(), &ReadOnlyArchiveInterface::testSuccess, this, &TestJob::onTestSuccess);

    bool ret = archiveInterface()->testArchive();

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

void TestJob::onTestSuccess()
{
    m_testSuccess = true;
}

bool TestJob::testSucceeded()
{
    return m_testSuccess;
}

801
} // namespace Kerfuffle
802

803