filtersylpheed.cpp 10 KB
Newer Older
1 2
/*
  filtersylpheed.cpp  -  Sylpheed maildir mail import
3

4
  SPDX-FileCopyrightText: 2005 Danny Kukawka <danny.kukawka@web.de>
Laurent Montel's avatar
Laurent Montel committed
5
  SPDX-FileCopyrightText: 2012-2021 Laurent Montel <montel@kde.org>
6 7 8

  SPDX-License-Identifier: GPL-2.0-or-later
*/
9 10 11 12

#include "filtersylpheed.h"

#include <KLocalizedString>
Laurent Montel's avatar
Laurent Montel committed
13
#include <QFileDialog>
14 15 16 17 18 19 20 21 22
#include "mailimporter_debug.h"
#include <QDomDocument>
#include <QDomElement>

using namespace MailImporter;

class MailImporter::FilterSylpheedPrivate
{
public:
Laurent Montel's avatar
Laurent Montel committed
23 24
    int mImportDirDone = 0;
    int mTotalDir = 0;
25 26
};
/** Default constructor. */
Laurent Montel's avatar
Laurent Montel committed
27 28 29 30 31 32 33 34 35 36
FilterSylpheed::FilterSylpheed()
    : Filter(i18n("Import Sylpheed Maildirs and Folder Structure"),
             QStringLiteral("Danny Kukawka"),
             i18n("<p><b>Sylpheed import filter</b></p>"
                  "<p>Select the base directory of the Sylpheed mailfolder you want to import "
                  "(usually: ~/Mail ).</p>"
                  "<p>Since it is possible to recreate the folder structure, the folders "
                  "will be stored under: \"Sylpheed-Import\" in your local folder.</p>"
                  "<p>This filter also recreates the status of message, e.g. new or forwarded.</p>"))
    , d(new MailImporter::FilterSylpheedPrivate)
37 38 39 40 41 42 43 44 45
{
}

/** Destructor. */
FilterSylpheed::~FilterSylpheed()
{
    delete d;
}

46 47 48 49 50 51 52 53 54
QString FilterSylpheed::isMailerFound()
{
    QDir directory(FilterSylpheed::defaultSettingsPath());
    if (directory.exists()) {
        return i18nc("name of sylpheed application", "Sylpheed");
    }
    return {};
}

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
QString FilterSylpheed::defaultSettingsPath()
{
    return QDir::homePath() + QLatin1String("/.sylpheed-2.0/");
}

QString FilterSylpheed::localMailDirPath()
{
    QFile folderListFile(FilterSylpheed::defaultSettingsPath() + QLatin1String("/folderlist.xml"));
    if (folderListFile.exists()) {
        QDomDocument doc;
        QString errorMsg;
        int errorRow;
        int errorCol;
        if (!doc.setContent(&folderListFile, &errorMsg, &errorRow, &errorCol)) {
            qCDebug(MAILIMPORTER_LOG) << "Unable to load document.Parse error in line " << errorRow
                                      << ", col " << errorCol << ": " << errorMsg;
            return QString();
        }
        QDomElement settings = doc.documentElement();

        if (settings.isNull()) {
            return QString();
        }

        for (QDomElement e = settings.firstChildElement(); !e.isNull(); e = e.nextSiblingElement()) {
            if (e.tagName() == QLatin1String("folder")) {
                if (e.hasAttribute(QStringLiteral("type"))) {
                    if (e.attribute(QStringLiteral("type")) == QLatin1String("mh")) {
                        return e.attribute(QStringLiteral("path"));
                    }
                }
            }
        }
    }
    return QString();
}

/** Recursive import of Sylpheed maildir. */
void FilterSylpheed::import()
{
    QString homeDir = localMailDirPath();
    if (homeDir.isEmpty()) {
        homeDir = QDir::homePath();
    }
    // Select directory from where I have to import files
Laurent Montel's avatar
Laurent Montel committed
100
    const QString maildir = QFileDialog::getExistingDirectory(nullptr, QString(), homeDir);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    if (!maildir.isEmpty()) {
        importMails(maildir);
    }
}

void FilterSylpheed::processDirectory(const QString &path)
{
    QDir dir(path);
    const QStringList rootSubDirs = dir.entryList(QStringList(QStringLiteral("[^\\.]*")), QDir::Dirs, QDir::Name);
    QStringList::ConstIterator end = rootSubDirs.constEnd();
    for (QStringList::ConstIterator filename = rootSubDirs.constBegin(); filename != end; ++filename) {
        if (filterInfo()->shouldTerminate()) {
            break;
        }
        importDirContents(dir.filePath(*filename));
Laurent Montel's avatar
Laurent Montel committed
116
        filterInfo()->setOverall((d->mTotalDir > 0) ? (int)((float)d->mImportDirDone / d->mTotalDir * 100) : 0);
117 118 119 120 121 122
        ++d->mImportDirDone;
    }
}

void FilterSylpheed::importMails(const QString &maildir)
{
123
    if (maildir.isEmpty()) {
124 125 126
        filterInfo()->alert(i18n("No directory selected."));
        return;
    }
127
    setMailDir(maildir);
128 129 130 131
    /**
    * If the user only select homedir no import needed because
    * there should be no files and we surely import wrong files.
    */
132
    if (mailDir() == QDir::homePath() || mailDir() == (QDir::homePath() + QLatin1Char('/'))) {
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        filterInfo()->addErrorLogEntry(i18n("No files found for import."));
    } else {
        filterInfo()->setOverall(0);

        d->mImportDirDone = 0;

        /** Recursive import of the MailFolders */
        QDir dir(mailDir());

        d->mTotalDir = Filter::countDirectory(dir, false);
        processDirectory(mailDir());

        filterInfo()->addInfoLogEntry(i18n("Finished importing emails from %1", mailDir()));
        if (countDuplicates() > 0) {
            filterInfo()->addInfoLogEntry(i18np("1 duplicate message not imported", "%1 duplicate messages not imported", countDuplicates()));
        }
    }
    if (filterInfo()->shouldTerminate()) {
        filterInfo()->addInfoLogEntry(i18n("Finished import, canceled by user."));
    }
153
    clearCountDuplicate();
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    filterInfo()->setCurrent(100);
    filterInfo()->setOverall(100);
}

/**
 * Import of a directory contents.
 * @param info Information storage for the operation.
 * @param dirName The name of the directory to import.
 */
void FilterSylpheed::importDirContents(const QString &dirName)
{
    if (filterInfo()->shouldTerminate()) {
        return;
    }

    /** Here Import all archives in the current dir */
    importFiles(dirName);

    /** If there are subfolders, we import them one by one */
    processDirectory(dirName);
}

bool FilterSylpheed::excludeFile(const QString &file)
{
Laurent Montel's avatar
Laurent Montel committed
178 179 180
    if (file.endsWith(QLatin1String(".sylpheed_cache"))
        || file.endsWith(QLatin1String(".sylpheed_mark"))
        || file.endsWith(QLatin1String(".mh_sequences"))) {
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
        return true;
    }
    return false;
}

QString FilterSylpheed::defaultInstallFolder() const
{
    return i18nc("define folder name where we will import sylpheed mails", "Sylpheed-Import") + QLatin1Char('/');
}

QString FilterSylpheed::markFile() const
{
    return QStringLiteral(".sylpheed_mark");
}

/**
 * Import the files within a Folder.
 * @param info Information storage for the operation.
 * @param dirName The name of the directory to import.
 */
void FilterSylpheed::importFiles(const QString &dirName)
{
    QDir dir(dirName);
    QString _path;
    bool generatedPath = false;

    QHash<QString, unsigned long> msgflags;

    QDir importDir(dirName);
    const QString defaultInstallPath = defaultInstallFolder();

    const QStringList files = importDir.entryList(QStringList(QStringLiteral("[^\\.]*")), QDir::Files, QDir::Name);
    int currentFile = 1, numFiles = files.size();

    readMarkFile(dir.filePath(markFile()), msgflags);

    QStringList::ConstIterator end(files.constEnd());
    for (QStringList::ConstIterator mailFile = files.constBegin(); mailFile != end; ++mailFile, ++currentFile) {
        if (filterInfo()->shouldTerminate()) {
            return;
        }
        QString _mfile = *mailFile;
        if (!excludeFile(_mfile)) {
            if (!generatedPath) {
                _path = defaultInstallPath;
                QString _tmp = dir.filePath(*mailFile);
227
                _tmp.remove(_tmp.length() - _mfile.length() - 1, _mfile.length() + 1);
228 229 230 231 232 233 234 235 236
                _path += _tmp.remove(mailDir(), Qt::CaseSensitive);
                QString _info = _path;
                filterInfo()->addInfoLogEntry(i18n("Import folder %1...", _info.remove(0, 15)));

                filterInfo()->setFrom(_info);
                filterInfo()->setTo(_path);
                generatedPath = true;
            }

Laurent Montel's avatar
Laurent Montel committed
237
            MailImporter::MessageStatus status;
238 239 240 241 242
            if (msgflags[_mfile]) {
                status = msgFlagsToString((msgflags[_mfile]));
            } else {
                status.setRead(true);    // 0 == read
            }
Laurent Montel's avatar
Laurent Montel committed
243
            if (!importMessage(_path, dir.filePath(*mailFile), filterInfo()->removeDupMessage(), status)) {
Laurent Montel's avatar
Laurent Montel committed
244
                filterInfo()->addErrorLogEntry(i18n("Could not import %1", *mailFile));
245
            }
Laurent Montel's avatar
Laurent Montel committed
246
            filterInfo()->setCurrent((int)((float)currentFile / numFiles * 100));
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
        }
    }
}

void FilterSylpheed::readMarkFile(const QString &path, QHash<QString, unsigned long> &dict)
{
    /* Each sylpheed mail directory contains a .sylpheed_mark file which
    * contains all the flags for each messages. The layout of this file
    * is documented in the source code of sylpheed: in procmsg.h for
    * the flag bits, and procmsg.c.
    *
    * Note that the mark file stores 32 bit unsigned integers in the
    * platform's native "endianness".
    *
    * The mark file starts with a 32 bit unsigned integer with a version
    * number. It is then followed by pairs of 32 bit unsigned integers,
    * the first one with the message file name (which is a number),
    * and the second one with the actual message flags */

    quint32 in, flags;
    QFile file(path);

    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }

    QDataStream stream(&file);

    if (Q_BYTE_ORDER == Q_LITTLE_ENDIAN) {
        stream.setByteOrder(QDataStream::LittleEndian);
    }

    /* Read version; if the value is reasonably too big, we're looking
    * at a file created on another platform. I don't have any test
    * marks/folders, so just ignoring this case */
    stream >> in;
Laurent Montel's avatar
Laurent Montel committed
283
    if (in > (quint32)0xffff) {
284 285 286 287 288 289 290 291 292 293 294
        return;
    }

    while (!stream.atEnd()) {
        if (filterInfo()->shouldTerminate()) {
            file.close();
            return;
        }
        stream >> in;
        stream >> flags;
        QString s;
Laurent Montel's avatar
Laurent Montel committed
295
        s.setNum((uint)in);
296 297 298 299
        dict.insert(s, flags);
    }
}

Laurent Montel's avatar
Laurent Montel committed
300
MailImporter::MessageStatus FilterSylpheed::msgFlagsToString(unsigned long flags)
301
{
Laurent Montel's avatar
Laurent Montel committed
302
    MailImporter::MessageStatus status;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    /* see sylpheed's procmsg.h */
    if (flags  & 2UL) {
        status.setRead(false);
    }
    if ((flags  & 3UL) == 0UL) {
        status.setRead(true);
    }
    if (flags  & 8UL) {
        status.setDeleted(true);
    }
    if (flags  & 16UL) {
        status.setReplied(true);
    }
    if (flags  & 32UL) {
        status.setForwarded(true);
    }
    return status;
}