aboutsummaryrefslogtreecommitdiff
path: root/src/qt_common/util/compress.cpp
blob: 94dca41151e87b42a310b914625f0b6928cbfb74 (plain) (blame)
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

#include "compress.h"
#include "quazipfileinfo.h"

#include <QDirIterator>
#include <quazipfile.h>

/** This is a modified version of JlCompress **/
namespace QtCommon::Compress {

bool compressDir(QString fileCompressed,
                 QString dir,
                 const Options &options,
                 QtCommon::QtProgressCallback callback)
{
    // Create zip
    QuaZip zip(fileCompressed);
    QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
    if (!zip.open(QuaZip::mdCreate)) {
        QFile::remove(fileCompressed);
        return false;
    }

    // See how big the overall fs structure is
    // good approx. of total progress
    // TODO(crueter): QDirListing impl... or fs::recursive_dir_iterator
    QDirIterator iter(dir,
                      QDir::NoDotAndDotDot | QDir::Hidden | QDir::Files,
                      QDirIterator::Subdirectories);

    std::size_t total = 0;
    while (iter.hasNext()) {
        total += iter.nextFileInfo().size();
    }

    std::size_t progress = 0;
    callback(total, progress);

    // Add the files and subdirectories
    if (!compressSubDir(&zip, dir, dir, options, total, progress, callback)) {
        QFile::remove(fileCompressed);
        return false;
    }

    // Close zip
    zip.close();
    if (zip.getZipError() != 0) {
        QFile::remove(fileCompressed);
        return false;
    }

    return true;
}

bool compressSubDir(QuaZip *zip,
                    QString dir,
                    QString origDir,
                    const Options &options,
                    std::size_t total,
                    std::size_t &progress,
                    QtProgressCallback callback)
{
    // zip: object where to add the file
    // dir: current real directory
    // origDir: original real directory
    // (path(dir)-path(origDir)) = path inside the zip object

    if (!zip)
        return false;
    if (zip->getMode() != QuaZip::mdCreate && zip->getMode() != QuaZip::mdAppend
        && zip->getMode() != QuaZip::mdAdd)
        return false;

    QDir directory(dir);
    if (!directory.exists())
        return false;


    QDir origDirectory(origDir);
    if (dir != origDir) {
        QuaZipFile dirZipFile(zip);
        std::unique_ptr<QuaZipNewInfo> qzni;
        qzni = std::make_unique<QuaZipNewInfo>(origDirectory.relativeFilePath(dir)
                                                   + QLatin1String("/"),
                                               dir);
        if (!dirZipFile.open(QIODevice::WriteOnly, *qzni, nullptr, 0, 0)) {
            return false;
        }
        dirZipFile.close();
    }

    // For each subfolder
    QFileInfoList subfiles = directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot
                                                     | QDir::Hidden | QDir::Dirs);
    for (const auto &file : std::as_const(subfiles)) {
        if (!compressSubDir(
                zip, file.absoluteFilePath(), origDir, options, total, progress, callback)) {
            return false;
        }
    }

    // For each file in directory
    QFileInfoList files = directory.entryInfoList(QDir::Hidden | QDir::Files);
    for (const auto &file : std::as_const(files)) {
        // If it's not a file or it's the compressed file being created
        if (!file.isFile() || file.absoluteFilePath() == zip->getZipName())
            continue;

        // Create relative name for the compressed file
        QString filename = origDirectory.relativeFilePath(file.absoluteFilePath());

        // Compress the file
        if (!compressFile(zip, file.absoluteFilePath(), filename, options, total, progress, callback)) {
            return false;
        }
    }

    return true;
}

bool compressFile(QuaZip *zip,
                  QString fileName,
                  QString fileDest,
                  const Options &options,
                  std::size_t total,
                  std::size_t &progress,
                  QtCommon::QtProgressCallback callback)
{
    // zip: object where to add the file
    // fileName: real file name
    // fileDest: file name inside the zip object

    if (!zip)
        return false;
    if (zip->getMode() != QuaZip::mdCreate && zip->getMode() != QuaZip::mdAppend
        && zip->getMode() != QuaZip::mdAdd)
        return false;

    QuaZipFile outFile(zip);
    if (options.getDateTime().isNull()) {
        if (!outFile.open(QIODevice::WriteOnly,
                          QuaZipNewInfo(fileDest, fileName),
                          nullptr,
                          0,
                          options.getCompressionMethod(),
                          options.getCompressionLevel()))
            return false;
    } else {
        if (!outFile.open(QIODevice::WriteOnly,
                          QuaZipNewInfo(fileDest, fileName),
                          nullptr,
                          0,
                          options.getCompressionMethod(),
                          options.getCompressionLevel()))
            return false;
    }

    QFileInfo input(fileName);
    if (quazip_is_symlink(input)) {
        // Not sure if we should use any specialized codecs here.
        // After all, a symlink IS just a byte array. And
        // this is mostly for Linux, where UTF-8 is ubiquitous these days.
        QString path = quazip_symlink_target(input);
        QString relativePath = input.dir().relativeFilePath(path);
        outFile.write(QFile::encodeName(relativePath));
    } else {
        QFile inFile;
        inFile.setFileName(fileName);
        if (!inFile.open(QIODevice::ReadOnly)) {
            return false;
        }
        if (!copyData(inFile, outFile, total, progress, callback) || outFile.getZipError() != UNZ_OK) {
            return false;
        }
        inFile.close();
    }

    outFile.close();
    return outFile.getZipError() == UNZ_OK;
}

bool copyData(QIODevice &inFile,
              QIODevice &outFile,
              std::size_t total,
              std::size_t &progress,
              QtProgressCallback callback)
{
    while (!inFile.atEnd()) {
        char buf[4096];
        qint64 readLen = inFile.read(buf, 4096);
        if (readLen <= 0)
            return false;
        if (outFile.write(buf, readLen) != readLen)
            return false;

        progress += readLen;
        if (!callback(total, progress)) {
            return false;
        }
    }
    return true;
}

QStringList extractDir(QString fileCompressed, QString dir, QtCommon::QtProgressCallback callback)
{
    // Open zip
    QuaZip zip(fileCompressed);
    return extractDir(zip, dir, callback);
}

QStringList extractDir(QuaZip &zip, const QString &dir, QtCommon::QtProgressCallback callback)
{
    if (!zip.open(QuaZip::mdUnzip)) {
        return QStringList();
    }
    QString cleanDir = QDir::cleanPath(dir);
    QDir directory(cleanDir);
    QString absCleanDir = directory.absolutePath();
    if (!absCleanDir.endsWith(QLatin1Char('/'))) // It only ends with / if it's the FS root.
        absCleanDir += QLatin1Char('/');
    QStringList extracted;
    if (!zip.goToFirstFile()) {
        return QStringList();
    }

    std::size_t total = 0;
    for (const QuaZipFileInfo64 &info : zip.getFileInfoList64()) {
        total += info.uncompressedSize;
    }

    std::size_t progress = 0;
    callback(total, progress);

    do {
        QString name = zip.getCurrentFileName();
        QString absFilePath = directory.absoluteFilePath(name);
        QString absCleanPath = QDir::cleanPath(absFilePath);
        if (!absCleanPath.startsWith(absCleanDir))
            continue;
        if (!extractFile(&zip, QLatin1String(""), absFilePath, total, progress, callback)) {
            removeFile(extracted);
            return QStringList();
        }
        extracted.append(absFilePath);
    } while (zip.goToNextFile());

    // Close zip
    zip.close();
    if (zip.getZipError() != 0) {
        removeFile(extracted);
        return QStringList();
    }

    return extracted;
}

bool extractFile(QuaZip *zip,
                 QString fileName,
                 QString fileDest,
                 std::size_t total,
                 std::size_t &progress,
                 QtCommon::QtProgressCallback callback)
{
    // zip: object where to add the file
    // filename: real file name
    // fileincompress: file name of the compressed file

    if (!zip)
        return false;
    if (zip->getMode() != QuaZip::mdUnzip)
        return false;

    if (!fileName.isEmpty())
        zip->setCurrentFile(fileName);
    QuaZipFile inFile(zip);
    if (!inFile.open(QIODevice::ReadOnly) || inFile.getZipError() != UNZ_OK)
        return false;

    // Check existence of resulting file
    QDir curDir;
    if (fileDest.endsWith(QLatin1String("/"))) {
        if (!curDir.mkpath(fileDest)) {
            return false;
        }
    } else {
        if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) {
            return false;
        }
    }

    QuaZipFileInfo64 info;
    if (!zip->getCurrentFileInfo(&info))
        return false;

    QFile::Permissions srcPerm = info.getPermissions();
    if (fileDest.endsWith(QLatin1String("/")) && QFileInfo(fileDest).isDir()) {
        if (srcPerm != 0) {
            QFile(fileDest).setPermissions(srcPerm);
        }
        return true;
    }

    if (info.isSymbolicLink()) {
        QString target = QFile::decodeName(inFile.readAll());
        return QFile::link(target, fileDest);
    }

    // Open resulting file
    QFile outFile;
    outFile.setFileName(fileDest);
    if (!outFile.open(QIODevice::WriteOnly))
        return false;

    // Copy data
    if (!copyData(inFile, outFile, total, progress, callback) || inFile.getZipError() != UNZ_OK) {
        outFile.close();
        removeFile(QStringList(fileDest));
        return false;
    }
    outFile.close();

    // Close file
    inFile.close();
    if (inFile.getZipError() != UNZ_OK) {
        removeFile(QStringList(fileDest));
        return false;
    }

    if (srcPerm != 0) {
        outFile.setPermissions(srcPerm);
    }
    return true;
}

bool removeFile(QStringList listFile)
{
    bool ret = true;
    // For each file
    for (int i = 0; i < listFile.count(); i++) {
        // Remove
        ret = ret && QFile::remove(listFile.at(i));
    }
    return ret;
}

} // namespace QtCommon::Compress