File: comiccreator.cpp

package info (click to toggle)
kio-extras 4%3A22.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,768 kB
  • sloc: cpp: 26,898; ansic: 4,443; perl: 1,058; xml: 97; sh: 69; python: 28; makefile: 9
file content (253 lines) | stat: -rw-r--r-- 8,122 bytes parent folder | download
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
/**
 * This file is part of the KDE libraries
 *
 * Comic Book Thumbnailer for KDE 4 v0.1
 * Creates cover page previews for comic-book files (.cbr/z/t).
 * SPDX-FileCopyrightText: 2009 Harsh J <harsh@harshj.com>
 *
 * Some code borrowed from Okular's comicbook generators,
 * by Tobias Koenig <tokoe@kde.org>
 *
 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
 */

// comiccreator.cpp

#include "comiccreator.h"
#include "thumbnail-comic-logsettings.h"

#include "macros.h"

#include <KZip>
#include <KTar>
#include <K7Zip>

#include <memory>

#include <QFile>
#include <QEventLoop>
#include <QMimeDatabase>
#include <QMimeType>
#include <QProcess>
#include <QStandardPaths>
#include <QTemporaryDir>

EXPORT_THUMBNAILER_WITH_JSON(ComicCreator, "comicbookthumbnail.json")

ComicCreator::ComicCreator() {}

bool ComicCreator::create(const QString& path, int width, int height, QImage& img)
{
    Q_UNUSED(width);
    Q_UNUSED(height);

    QImage cover;

    // Detect mime type.
    QMimeDatabase db;
    db.mimeTypeForFile(path, QMimeDatabase::MatchContent);
    const QMimeType mime = db.mimeTypeForFile(path, QMimeDatabase::MatchContent);

    if (mime.inherits("application/x-cbz") || mime.inherits("application/zip")) {
        // ZIP archive.
        cover = extractArchiveImage(path, ZIP);
    } else if (mime.inherits("application/x-cbt") ||
               mime.inherits("application/x-gzip") ||
               mime.inherits("application/x-tar")) {
        // TAR archive
        cover = extractArchiveImage(path, TAR);
    } else if (mime.inherits("application/x-cb7") || mime.inherits("application/x-7z-compressed")) {
        cover = extractArchiveImage(path, SEVENZIP);
    } else if (mime.inherits("application/x-cbr") || mime.inherits("application/x-rar")) {
        // RAR archive.
        cover = extractRARImage(path);
    }

    if (cover.isNull()) {
        qCDebug(KIO_THUMBNAIL_COMIC_LOG) << "Error creating the comic book thumbnail for" << path;
        return false;
    }

    // Copy the extracted cover to KIO::ThumbCreator's img reference.
    img = cover;

    return true;
}

void ComicCreator::filterImages(QStringList& entries)
{
    /// Sort case-insensitive, then remove non-image entries.
    QMap<QString, QString> entryMap;
    for (const QString& entry : qAsConst(entries)) {
        // Skip MacOS resource forks
        if (entry.startsWith(QLatin1String("__MACOSX"), Qt::CaseInsensitive) ||
                entry.startsWith(QLatin1String(".DS_Store"), Qt::CaseInsensitive)) {
            continue;
        }
        if (entry.endsWith(QLatin1String(".avif"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".bmp"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".gif"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".heif"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".jpeg"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".jxl"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".png"), Qt::CaseInsensitive) ||
                entry.endsWith(QLatin1String(".webp"), Qt::CaseInsensitive)) {
            entryMap.insert(entry.toLower(), entry);
        }
    }
    entries = entryMap.values();
}

QImage ComicCreator::extractArchiveImage(const QString& path, const ComicCreator::Type type)
{
    /// Extracts the cover image out of the .cbz or .cbt file.
    QScopedPointer<KArchive> cArchive;

    if (type==ZIP) {
        // Open the ZIP archive.
        cArchive.reset(new KZip(path));
    } else if (type==TAR) {
        // Open the TAR archive.
        cArchive.reset(new KTar(path));
    } else if (type==SEVENZIP) {
        // Open the 7z archive.
        cArchive.reset(new K7Zip(path));
    } else {
        // Reject all other types for this method.
        return QImage();
    }

    // Can our archive be opened?
    if (!cArchive->open(QIODevice::ReadOnly)) {
        return QImage();
    }

    // Get the archive's directory.
    const KArchiveDirectory* cArchiveDir = nullptr;
    cArchiveDir = cArchive->directory();
    if (!cArchiveDir) {
        return QImage();
    }

    QStringList entries;

    // Get and filter the entries from the archive.
    getArchiveFileList(entries, QString(), cArchiveDir);
    filterImages(entries);
    if (entries.isEmpty()) {
        return QImage();
    }

    // Extract the cover file.
    const KArchiveFile *coverFile = static_cast<const KArchiveFile*>
                                    (cArchiveDir->entry(entries[0]));
    if (!coverFile) {
        return QImage();
    }

    return QImage::fromData(coverFile->data());
}



void ComicCreator::getArchiveFileList(QStringList& entries, const QString& prefix,
                                      const KArchiveDirectory *dir)
{
    /// Recursively list all files in the ZIP archive into 'entries'.
    const auto dirEntries = dir->entries();
    for (const QString& entry : dirEntries) {
        const KArchiveEntry *e = dir->entry(entry);
        if (e->isDirectory()) {
            getArchiveFileList(entries, prefix + entry + '/',
                               static_cast<const KArchiveDirectory*>(e));
        } else if (e->isFile()) {
            entries.append(prefix + entry);
        }
    }
}

QImage ComicCreator::extractRARImage(const QString& path)
{
    /// Extracts the cover image out of the .cbr file.

    // Check if unrar is available. Get its path in 'unrarPath'.
    static const QString unrar = unrarPath();
    if (unrar.isEmpty()) {
        return QImage();
    }

    // Get the files and filter the images out.
    QStringList entries = getRARFileList(path, unrar);
    filterImages(entries);
    if (entries.isEmpty()) {
        return QImage();
    }

    // Extract the cover file alone. Use verbose paths.
    // unrar x -n<file> path/to/archive /path/to/temp
    QTemporaryDir cUnrarTempDir;
    runProcess(unrar, {"x", "-n" + entries[0], path, cUnrarTempDir.path()});

    // Load cover file data into image.
    QImage cover;
    cover.load(cUnrarTempDir.path() + QDir::separator() + entries[0]);

    return cover;
}

QStringList ComicCreator::getRARFileList(const QString& path,
        const QString& unrarPath)
{
    /// Get a verbose unrar listing so we can extract a single file later.
    // CMD: unrar vb /path/to/archive
    QStringList entries;
    runProcess(unrarPath, {"vb", path});
    entries = QString::fromLocal8Bit(m_stdOut).split('\n', Qt::SkipEmptyParts);
    return entries;
}

QString ComicCreator::unrarPath() const
{
    /// Check the standard paths to see if a suitable unrar is available.
    QString unrar = QStandardPaths::findExecutable("unrar");
    if (unrar.isEmpty()) {
        unrar = QStandardPaths::findExecutable("unrar-nonfree");
    }
    if (unrar.isEmpty()) {
        unrar = QStandardPaths::findExecutable("rar");
    }
    if (!unrar.isEmpty()) {
        QProcess proc;
        proc.start(unrar, {"-version"});
        proc.waitForFinished(-1);
        const QStringList lines = QString::fromLocal8Bit(proc.readAllStandardOutput()).split
                                  ('\n', Qt::SkipEmptyParts);
        if (!lines.isEmpty()) {
            if (lines.first().startsWith(QLatin1String("RAR ")) || lines.first().startsWith(QLatin1String("UNRAR "))) {
                return unrar;
            }
        }
    }
    qCWarning(KIO_THUMBNAIL_COMIC_LOG) << "A suitable version of unrar is not available.";
    return QString();
}

int ComicCreator::runProcess(const QString& processPath, const QStringList& args)
{
    /// Run a process and store stdout data in a buffer.

    QProcess process;
    process.setProcessChannelMode(QProcess::SeparateChannels);

    process.setProgram(processPath);
    process.setArguments(args);
    process.start(QIODevice::ReadWrite | QIODevice::Unbuffered);

    auto ret = process.waitForFinished(-1);
    m_stdOut = process.readAllStandardOutput();

    return ret;
}

#include "comiccreator.moc"