kpeoplevcard.cpp 6.7 KB
Newer Older
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
/*
    Copyright (C) 2015 Aleix Pol Gonzalez <aleixpol@kde.org>
    Copyright (C) 2015 Martin Klapetek <mklapetek@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "kpeoplevcard.h"
#include <QDebug>
#include <QImage>
#include <QDir>
#include <QStandardPaths>
#include <KContacts/VCardConverter>
#include <KContacts/Picture>
#include <KPeopleBackend/BasePersonsDataSource>
#include <KLocalizedString>

#include <KPluginFactory>
#include <KPluginLoader>

using namespace KPeople;

Q_GLOBAL_STATIC_WITH_ARGS(QString, vcardsLocation, (QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + ("/kpeoplevcard")))

class VCardContact : public AbstractContact
{
public:
    VCardContact() {}
    VCardContact(const KContacts::Addressee& addr) : m_addressee(addr) {}
    void setAddressee(const KContacts::Addressee& addr) { m_addressee = addr; }

    QVariant customProperty(const QString & key) const override
    {
        QVariant ret;
        if (key == NameProperty) {
            const QString name = m_addressee.realName();
            if (!name.isEmpty()) {
                return name;
            }

            // If both first and last name are set combine them to a full name
            if (!m_addressee.givenName().isEmpty() && !m_addressee.familyName().isEmpty())
                return i18nc("given-name family-name", "%1 %2", m_addressee.givenName(), m_addressee.familyName());

            // If only one of them is set just return what we know
            if (!m_addressee.givenName().isEmpty())
                return m_addressee.givenName();
            if (!m_addressee.familyName().isEmpty())
                return m_addressee.familyName();

            // Fall back to other identifiers
            if (!m_addressee.preferredEmail().isEmpty()) {
                return m_addressee.preferredEmail();
            }
            if (!m_addressee.phoneNumbers().isEmpty()) {
                return m_addressee.phoneNumbers().at(0).number();
            }
            return QVariant();
        } else if (key == EmailProperty)
            return m_addressee.preferredEmail();
        else if (key == AllEmailsProperty)
            return m_addressee.emails();
        else if (key == PictureProperty)
            return m_addressee.photo().data();
        else if (key == AllPhoneNumbersProperty) {
            const auto phoneNumbers = m_addressee.phoneNumbers();
            QVariantList numbers;
            for (const KContacts::PhoneNumber &phoneNumber : phoneNumbers) {
                // convert from KContacts specific format to QString
                numbers << phoneNumber.number();
            }
            return numbers;
        } else if (key == PhoneNumberProperty) {
            return m_addressee.phoneNumbers().isEmpty() ? QVariant() : m_addressee.phoneNumbers().at(0).number();
        }

        return ret;
    }

    static QString createUri(const QString& path) {
        return QStringLiteral("vcard:/") + path;
    }
private:
    KContacts::Addressee m_addressee;
};

class VCardDataSource : public KPeople::BasePersonsDataSource
{
public:
    VCardDataSource(QObject *parent, const QVariantList &data);
    ~VCardDataSource() override;
    QString sourcePluginId() const override;

    KPeople::AllContactsMonitor* createAllContactsMonitor() override;
};

KPeopleVCard::KPeopleVCard()
    : KPeople::AllContactsMonitor()
    , m_fs(new KDirWatch(this))
{
    QDir().mkpath(*vcardsLocation);

    QDir dir(*vcardsLocation);
    const QStringList subdirs = dir.entryList(QDir::AllDirs | QDir::NoDotDot); // includes '.', ie. vcards from no subdir
    QStringList entries;

    for (const QString &subdirName : subdirs) {
        QDir subdir(dir.absoluteFilePath(subdirName));
        const QFileInfoList subdirVcards = subdir.entryInfoList({"*.vcard", "*.vcf"});
        for (const QFileInfo &vcardFile : subdirVcards) {
            entries << vcardFile.absoluteFilePath();
        }
    }

    for (const QString& entry : qAsConst(entries)) {
        processVCard(entry);
    }

    m_fs->addDir(dir.absolutePath(), KDirWatch::WatchDirOnly | KDirWatch::WatchSubDirs);
    connect(m_fs, &KDirWatch::dirty, this, [this](const QString& path){ if (QFileInfo(path).isFile()) processVCard(path); });
    connect(m_fs, &KDirWatch::created, this, &KPeopleVCard::processVCard);
    connect(m_fs, &KDirWatch::deleted, this, &KPeopleVCard::deleteVCard);
}

KPeopleVCard::~KPeopleVCard()
{}

QMap<QString, AbstractContact::Ptr> KPeopleVCard::contacts()
{
    return m_contactForUri;
}

void KPeopleVCard::processVCard(const QString &path)
{
    m_fs->addFile(path);

    QFile f(path);
    bool b = f.open(QIODevice::ReadOnly);
    if (!b) {
        qWarning() << "error: couldn't open:" << path;
        return;
    }

    KContacts::VCardConverter conv;
    const KContacts::Addressee addressee = conv.parseVCard(f.readAll());

    QString uri = VCardContact::createUri(path);
    auto it = m_contactForUri.find(uri);
    if (it != m_contactForUri.end()) {
        static_cast<VCardContact*>(it->data())->setAddressee(addressee);
        Q_EMIT contactChanged(uri, *it);
    } else {
        KPeople::AbstractContact::Ptr contact(new VCardContact(addressee));
        m_contactForUri.insert(uri, contact);
        Q_EMIT contactAdded(uri, contact);
    }
}

void KPeopleVCard::deleteVCard(const QString &path)
{
    QString uri = VCardContact::createUri(path);
    int r = m_contactForUri.remove(uri);
    Q_ASSERT(r);
    Q_EMIT contactRemoved(uri);
}

QString KPeopleVCard::contactsVCardPath()
{
    return *vcardsLocation;
}

VCardDataSource::VCardDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
    Q_UNUSED(args);
}

VCardDataSource::~VCardDataSource()
{
}

QString VCardDataSource::sourcePluginId() const
{
    return QStringLiteral("vcard");
}

AllContactsMonitor* VCardDataSource::createAllContactsMonitor()
{
    return new KPeopleVCard();
}

K_PLUGIN_FACTORY_WITH_JSON( VCardDataSourceFactory, "kpeoplevcard.json", registerPlugin<VCardDataSource>(); )
K_EXPORT_PLUGIN( VCardDataSourceFactory("kpeoplevcard") )

#include "kpeoplevcard.moc"