File indexing completed on 2024-04-14 05:19:17

0001 /*
0002  * SPDX-FileCopyrightText: 2019 Jonah BrĂ¼chert <jbb@kaidan.im>
0003  *
0004  * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 
0007 #include "contactimporter.h"
0008 
0009 #include <QDebug>
0010 #include <QFile>
0011 
0012 #include <KContacts/VCardConverter>
0013 #include <KPeople/PersonPluginManager>
0014 
0015 ContactImporter::ContactImporter(QObject *parent)
0016     : QObject(parent)
0017 {
0018 }
0019 
0020 void ContactImporter::startImport()
0021 {
0022     m_dialog = std::make_unique<QFileDialog>();
0023     m_dialog->setFileMode(QFileDialog::ExistingFile);
0024     connect(m_dialog.get(), &QFileDialog::finished, this, [=] {
0025         const auto selectedFiles = m_dialog->selectedFiles();
0026         if (!selectedFiles.empty()) {
0027             importVCards(QUrl::fromLocalFile(m_dialog->selectedFiles().first()));
0028         }
0029     });
0030     m_dialog->open();
0031 }
0032 
0033 void ContactImporter::importVCards(const QUrl &path)
0034 {
0035 #ifdef Q_OS_ANDROID
0036     QFile inputFile(path.toString());
0037 #else
0038     QFile inputFile(path.toLocalFile());
0039 #endif
0040 
0041     if (!inputFile.open(QIODevice::ReadOnly)) {
0042         qWarning() << "Couldn't read vCard to import: Couldn't open file for reading";
0043         return;
0044     }
0045 
0046     const auto importedVCards = m_converter.parseVCards(inputFile.readAll());
0047     for (const auto &adr : importedVCards) {
0048         QVariantMap properties;
0049         properties[QStringLiteral("vcard")] = m_converter.exportVCard(adr, KContacts::VCardConverter::v3_0);
0050         KPeople::PersonPluginManager::addContact(properties);
0051     }
0052 }