File: ebookcreator.cpp

package info (click to toggle)
kio-extras 4%3A25.04.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 31,928 kB
  • sloc: cpp: 28,852; ansic: 3,084; perl: 1,048; xml: 116; sh: 92; python: 28; makefile: 9
file content (333 lines) | stat: -rw-r--r-- 10,461 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
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
/*
 * SPDX-FileCopyrightText: 2019 Kai Uwe Broulik <kde@broulik.de>
 *
 * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
 */

#include "ebookcreator.h"

#include <QFile>
#include <QImage>
#include <QMap>
#include <QMimeDatabase>
#include <QUrl>
#include <QXmlStreamReader>

#include <KPluginFactory>
#include <KZip>

K_PLUGIN_CLASS_WITH_JSON(EbookCreator, "ebookthumbnail.json")

EbookCreator::EbookCreator(QObject *parent, const QVariantList &args)
    : KIO::ThumbnailCreator(parent, args)
{
}

EbookCreator::~EbookCreator() = default;

KIO::ThumbnailResult EbookCreator::create(const KIO::ThumbnailRequest &request)
{
    const QString path = request.url().toLocalFile();

    if (request.mimeType() == QLatin1String("application/epub+zip")) {
        return createEpub(path);

    } else if (request.mimeType() == QLatin1String("application/x-fictionbook+xml")) {
        QFile file(path);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            return KIO::ThumbnailResult::fail();
        }

        return createFb2(&file);

    } else if (request.mimeType() == QLatin1String("application/x-zip-compressed-fb2")) {
        KZip zip(path);
        if (!zip.open(QIODevice::ReadOnly)) {
            return KIO::ThumbnailResult::fail();
        }

        QScopedPointer<QIODevice> zipDevice;

        const auto entries = zip.directory()->entries();
        for (const QString &entryPath : entries) {
            if (entries.count() > 1 && !entryPath.endsWith(QLatin1String(".fb2"))) { // can this done a bit more cleverly?
                continue;
            }

            const auto *entry = zip.directory()->file(entryPath);
            if (!entry) {
                return KIO::ThumbnailResult::fail();
            }

            zipDevice.reset(entry->createDevice());
        }

        return createFb2(zipDevice.data());
    }

    return KIO::ThumbnailResult::fail();
}

KIO::ThumbnailResult EbookCreator::createEpub(const QString &path)
{
    KZip zip(path);
    if (!zip.open(QIODevice::ReadOnly)) {
        return KIO::ThumbnailResult::fail();
    }

    QScopedPointer<QIODevice> zipDevice;
    QString opfPath;
    QString coverHref;

    // First figure out where the OPF file with metadata is
    const auto *entry = zip.directory()->file(QStringLiteral("META-INF/container.xml"));

    if (!entry) {
        return KIO::ThumbnailResult::fail();
    }

    zipDevice.reset(entry->createDevice());

    QXmlStreamReader xml(zipDevice.data());
    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();

        if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
            opfPath = xml.attributes().value(QStringLiteral("full-path")).toString();
            break;
        }
    }

    if (opfPath.isEmpty()) {
        return KIO::ThumbnailResult::fail();
    }

    // Now read the OPF file and look for a <meta name="cover" content="...">
    entry = zip.directory()->file(opfPath);
    if (!entry) {
        return KIO::ThumbnailResult::fail();
    }

    zipDevice.reset(entry->createDevice());

    xml.setDevice(zipDevice.data());

    bool inMetadata = false;
    bool inManifest = false;
    QString coverId;
    QMap<QString, QString> itemHrefs;

    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();

        if (xml.name() == QLatin1String("metadata")) {
            if (xml.isStartElement()) {
                inMetadata = true;
            } else if (xml.isEndElement()) {
                inMetadata = false;
            }
            continue;
        }

        if (xml.name() == QLatin1String("manifest")) {
            if (xml.isStartElement()) {
                inManifest = true;
            } else if (xml.isEndElement()) {
                inManifest = false;
            }
            continue;
        }

        if (xml.isStartElement()) {
            if (inMetadata && (xml.name() == QLatin1String("meta"))) {
                const auto attributes = xml.attributes();
                if (attributes.value(QStringLiteral("name")) == QLatin1String("cover")) {
                    coverId = attributes.value(QStringLiteral("content")).toString();
                }
            } else if (inManifest && (xml.name() == QLatin1String("item"))) {
                const auto attributes = xml.attributes();
                const QString href = attributes.value(QStringLiteral("href")).toString();
                const QString id = attributes.value(QStringLiteral("id")).toString();
                if (!id.isEmpty() && !href.isEmpty()) {
                    // EPUB 3 has the "cover-image" property set
                    const auto properties = attributes.value(QStringLiteral("properties")).toString();
                    const auto propertyList = properties.split(QChar(' '), Qt::SkipEmptyParts);
                    if (propertyList.contains(QLatin1String("cover-image"))) {
                        coverHref = href;
                        break;
                    }
                    itemHrefs[id] = href;
                }
            } else {
                continue;
            }

            if (!coverId.isEmpty() && itemHrefs.contains(coverId)) {
                coverHref = itemHrefs[coverId];
                break;
            }
        }
    }

    if (coverHref.isEmpty()) {
        // Maybe we're lucky and the archive contains an iTunesArtwork file from iBooks
        entry = zip.directory()->file(QStringLiteral("iTunesArtwork"));
        if (entry) {
            zipDevice.reset(entry->createDevice());

            QImage image;
            bool okay = image.load(zipDevice.data(), "");

            return okay ? KIO::ThumbnailResult::pass(image) : KIO::ThumbnailResult::fail();
        }

        // Maybe there's a file called "cover" somewhere
        const QStringList entries = getEntryList(zip.directory(), QString());

        for (const QString &name : entries) {
            if (!name.contains(QLatin1String("cover"), Qt::CaseInsensitive)) {
                continue;
            }

            entry = zip.directory()->file(name);
            if (!entry) {
                continue;
            }

            zipDevice.reset(entry->createDevice());

            QImage image;
            bool success = image.load(zipDevice.data(), "");

            if (success) {
                return KIO::ThumbnailResult::pass(image);
            }
        }
        return KIO::ThumbnailResult::fail();
    }

    // Decode percent encoded URL
    QByteArray encoded = coverHref.toUtf8();
    coverHref = QUrl::fromPercentEncoding(encoded);

    // Make coverHref relative to OPF location
    const int lastOpfSlash = opfPath.lastIndexOf(QLatin1Char('/'));
    if (lastOpfSlash > -1) {
        QString basePath = opfPath.left(lastOpfSlash + 1);
        coverHref.prepend(basePath);
    }

    // Finally, just load the cover image file
    entry = zip.directory()->file(coverHref);
    if (entry) {
        zipDevice.reset(entry->createDevice());
        QImage image;
        image.load(zipDevice.data(), "");

        return KIO::ThumbnailResult::pass(image);
    }

    return KIO::ThumbnailResult::fail();
}

KIO::ThumbnailResult EbookCreator::createFb2(QIODevice *device)
{
    QString coverId;

    QXmlStreamReader xml(device);

    bool inFictionBook = false;
    bool inDescription = false;
    bool inTitleInfo = false;
    bool inCoverPage = false;

    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();

        if (xml.name() == QLatin1String("FictionBook")) {
            if (xml.isStartElement()) {
                inFictionBook = true;
            } else if (xml.isEndElement()) {
                break;
            }
        } else if (xml.name() == QLatin1String("description")) {
            if (xml.isStartElement()) {
                inDescription = true;
            } else if (xml.isEndElement()) {
                inDescription = false;
            }
        } else if (xml.name() == QLatin1String("title-info")) {
            if (xml.isStartElement()) {
                inTitleInfo = true;
            } else if (xml.isEndElement()) {
                inTitleInfo = false;
            }
        } else if (xml.name() == QLatin1String("coverpage")) {
            if (xml.isStartElement()) {
                inCoverPage = true;
            } else if (xml.isEndElement()) {
                inCoverPage = false;
            }
        }

        if (!inFictionBook) {
            continue;
        }

        if (inDescription) {
            if (inTitleInfo && inCoverPage) {
                if (xml.isStartElement() && xml.name() == QLatin1String("image")) {
                    const auto attributes = xml.attributes();

                    // value() wants a namespace but we don't care, so iterate until we find any "href"
                    for (const auto &attribute : attributes) {
                        if (attribute.name() == QLatin1String("href")) {
                            coverId = attribute.value().toString();
                            if (coverId.startsWith(QLatin1Char('#'))) {
                                coverId = coverId.mid(1);
                            }
                        }
                    }
                }
            }
        } else {
            if (!coverId.isEmpty() && xml.isStartElement() && xml.name() == QLatin1String("binary")) {
                if (xml.attributes().value(QStringLiteral("id")) == coverId) {
                    QImage image;
                    image.loadFromData(QByteArray::fromBase64(xml.readElementText().toLatin1()));
                    return KIO::ThumbnailResult::pass(image);
                }
            }
        }
    }

    return KIO::ThumbnailResult::fail();
}

QStringList EbookCreator::getEntryList(const KArchiveDirectory *dir, const QString &path)
{
    QStringList list;

    const QStringList entries = dir->entries();
    for (const QString &name : entries) {
        const KArchiveEntry *entry = dir->entry(name);

        QString fullPath = name;

        if (!path.isEmpty()) {
            fullPath.prepend(QLatin1Char('/'));
            fullPath.prepend(path);
        }

        if (entry->isFile()) {
            list << fullPath;
        } else {
            list << getEntryList(static_cast<const KArchiveDirectory *>(entry), fullPath);
        }
    }

    return list;
}

#include "ebookcreator.moc"
#include "moc_ebookcreator.cpp"