gmximportexportplugininterface.cpp 26 KB
Newer Older
Laurent Montel's avatar
Laurent Montel committed
1
/*
Laurent Montel's avatar
Laurent Montel committed
2
   Copyright (C) 2016-2020 Laurent Montel <montel@kde.org>
Laurent Montel's avatar
Laurent Montel committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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

   This program 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
   General Public License for more details.

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

#include "gmximportexportplugininterface.h"
Laurent Montel's avatar
Laurent Montel committed
21
#include "kaddressbook_importexport_gmx_debug.h"
Laurent Montel's avatar
Laurent Montel committed
22
23
24
#include <KLocalizedString>
#include <KActionCollection>
#include <QAction>
Laurent Montel's avatar
Laurent Montel committed
25
#include <QUrl>
Laurent Montel's avatar
Laurent Montel committed
26
27
28
29
30
31
32
33
#include <QFileDialog>
#include <PimCommon/RenameFileDialog>
#include <KMessageBox>
#include <QTemporaryFile>
#include <KJobWidgets>
#include <QTextStream>
#include <KAddressBookContactSelectionDialog>
#include <QPointer>
Laurent Montel's avatar
Laurent Montel committed
34
#include <importexportengine.h>
Laurent Montel's avatar
Laurent Montel committed
35
36
#include <KIOCore/kio/filecopyjob.h>

Laurent Montel's avatar
Laurent Montel committed
37
38
39
#define GMX_FILESELECTION_STRING i18n("GMX address book file (*.gmxa)")
const int typeHome = 0;
const int typeWork = 1;
Laurent Montel's avatar
Laurent Montel committed
40
const int typeOther = 2;
Laurent Montel's avatar
Laurent Montel committed
41
42
43
44
45
46
47
48
49
50
51
52
53

GMXImportExportPluginInterface::GMXImportExportPluginInterface(QObject *parent)
    : KAddressBookImportExport::KAddressBookImportExportPluginInterface(parent)
{
}

GMXImportExportPluginInterface::~GMXImportExportPluginInterface()
{
}

void GMXImportExportPluginInterface::createAction(KActionCollection *ac)
{
    QAction *action = ac->addAction(QStringLiteral("file_import_gmx"));
54
55
    action->setText(i18n("Import GMX file..."));
    action->setWhatsThis(i18n("Import contacts from a GMX address book file."));
Laurent Montel's avatar
Laurent Montel committed
56
    setImportActions(QList<QAction *>() << action);
57
    connect(action, &QAction::triggered, this, &GMXImportExportPluginInterface::slotImportGmx);
Laurent Montel's avatar
Laurent Montel committed
58

59
60
61
62
63
64
    action = ac->addAction(QStringLiteral("file_export_gmx"));
    action->setText(i18n("Export GMX file..."));
    action->setWhatsThis(i18n("Export contacts to a GMX address book file."));
    setExportActions(QList<QAction *>() << action);
    connect(action, &QAction::triggered, this, &GMXImportExportPluginInterface::slotExportGmx);
}
Laurent Montel's avatar
Laurent Montel committed
65

66
67
void GMXImportExportPluginInterface::exec()
{
Laurent Montel's avatar
Laurent Montel committed
68
    switch (mImportExportAction) {
69
    case Import:
Laurent Montel's avatar
Laurent Montel committed
70
        importGMX();
71
72
        break;
    case Export:
Laurent Montel's avatar
Laurent Montel committed
73
        exportGMX();
74
75
76
        break;
    }
}
Laurent Montel's avatar
Laurent Montel committed
77

78
79
80
81
void GMXImportExportPluginInterface::slotImportGmx()
{
    mImportExportAction = Import;
    Q_EMIT emitPluginActivated(this);
Laurent Montel's avatar
Laurent Montel committed
82
83
}

84
void GMXImportExportPluginInterface::slotExportGmx()
Laurent Montel's avatar
Laurent Montel committed
85
{
86
87
    mImportExportAction = Export;
    Q_EMIT emitPluginActivated(this);
Laurent Montel's avatar
Laurent Montel committed
88
}
Laurent Montel's avatar
Laurent Montel committed
89
90
91

void GMXImportExportPluginInterface::exportGMX()
{
Laurent Montel's avatar
Laurent Montel committed
92
93
    QPointer<KAddressBookImportExport::KAddressBookContactSelectionDialog> dlg
        = new KAddressBookImportExport::KAddressBookContactSelectionDialog(itemSelectionModel(), false, parentWidget());
Laurent Montel's avatar
Laurent Montel committed
94
95
    dlg->setMessageText(i18n("Which contact do you want to export?"));
    dlg->setDefaultAddressBook(defaultCollection());
Laurent Montel's avatar
Laurent Montel committed
96
    if (!dlg->exec()) {
Laurent Montel's avatar
Laurent Montel committed
97
98
99
100
101
102
103
        delete dlg;
        return;
    }
    const KContacts::AddresseeList contacts = dlg->selectedContacts().addressList();
    delete dlg;

    if (contacts.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
104
        KMessageBox::sorry(nullptr, i18n("You have not selected any contacts to export."));
Laurent Montel's avatar
Laurent Montel committed
105
106
107
108
109
        return;
    }

    KAddressBookImportExport::KAddressBookImportExportContactList contactLists;
    contactLists.setAddressList(contacts);
110
    QFileDialog::Options options = QFileDialog::DontConfirmOverwrite;
Laurent Montel's avatar
Laurent Montel committed
111
    QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QDir::homePath() + QStringLiteral("/addressbook.gmx")), GMX_FILESELECTION_STRING, nullptr, options);
Laurent Montel's avatar
Laurent Montel committed
112
113
114
115
    if (url.isEmpty()) {
        return;
    }

Laurent Montel's avatar
Laurent Montel committed
116
117
    if (QFileInfo::exists(url.isLocalFile()
                          ? url.toLocalFile() : url.path())) {
Laurent Montel's avatar
Laurent Montel committed
118
        if (url.isLocalFile() && QFileInfo::exists(url.toLocalFile())) {
Laurent Montel's avatar
Laurent Montel committed
119
            PimCommon::RenameFileDialog *dialog = new PimCommon::RenameFileDialog(url, false, parentWidget());
Laurent Montel's avatar
Laurent Montel committed
120
            const PimCommon::RenameFileDialog::RenameFileDialogResult result = static_cast<PimCommon::RenameFileDialog::RenameFileDialogResult>(dialog->exec());
Laurent Montel's avatar
Laurent Montel committed
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
            if (result == PimCommon::RenameFileDialog::RENAMEFILE_RENAME) {
                url = dialog->newName();
            } else if (result == PimCommon::RenameFileDialog::RENAMEFILE_IGNORE) {
                delete dialog;
                return;
            }
            delete dialog;
        }
    }

    if (!url.isLocalFile()) {
        QTemporaryFile tmpFile;
        if (!tmpFile.open()) {
            const QString txt = i18n("<qt>Unable to open file <b>%1</b></qt>", url.url());
            KMessageBox::error(parentWidget(), txt);
            return;
        }

        doExport(&tmpFile, contactLists.addressList());
        tmpFile.flush();
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite);
        KJobWidgets::setWindow(job, parentWidget());
        job->exec();
    } else {
        QString fileName = url.toLocalFile();
        QFile file(fileName);

        if (!file.open(QIODevice::WriteOnly)) {
            const QString txt = i18n("<qt>Unable to open file <b>%1</b>.</qt>", fileName);
            KMessageBox::error(parentWidget(), txt);
            return;
        }
Laurent Montel's avatar
Laurent Montel committed
153

Laurent Montel's avatar
Laurent Montel committed
154
155
156
        doExport(&file, contactLists.addressList());
        file.close();
    }
Laurent Montel's avatar
Laurent Montel committed
157
158
}

Laurent Montel's avatar
Laurent Montel committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
static bool checkDateTime(const QString &dateStr, QDateTime &dt)
{
    if (dateStr.isEmpty()) {
        return false;
    }

    dt = QDateTime::fromString(dateStr, Qt::ISODate);
    if (dt.isValid() && dt.date().year() > 1901) {
        return true;
    }
    dt.setDate(QDate());

    return false;
}

Laurent Montel's avatar
Laurent Montel committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
static const QString dateString(const QDateTime &dt)
{
    if (!dt.isValid()) {
        return QStringLiteral("1000-01-01 00:00:00");
    }
    QString d(dt.toString(Qt::ISODate));
    d[10] = ' '; // remove the "T" in the middle of the string
    return d;
}

static const QStringList assignedCategoriesSorted(const KContacts::AddresseeList &list)
{
    // Walk through the addressees and return a unique list of up to 31
    // categories, alphabetically sorted
    QStringList categoryList;
Laurent Montel's avatar
Laurent Montel committed
189
    const KContacts::Addressee *addressee = nullptr;
Laurent Montel's avatar
Laurent Montel committed
190
    for (KContacts::AddresseeList::ConstIterator addresseeIt = list.begin();
Laurent Montel's avatar
Laurent Montel committed
191
         addresseeIt != list.end() && categoryList.count() < 32; ++addresseeIt) {
Laurent Montel's avatar
Laurent Montel committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        addressee = &(*addresseeIt);
        if (addressee->isEmpty()) {
            continue;
        }
        const QStringList categories = addressee->categories();
        for (int i = 0; i < categories.count() && categoryList.count() < 32; ++i) {
            if (!categoryList.contains(categories[i])) {
                categoryList.append(categories[i]);
            }
        }
    }
    categoryList.sort();
    return categoryList;
}

void GMXImportExportPluginInterface::doExport(QFile *fp, const KContacts::AddresseeList &list) const
{
Laurent Montel's avatar
Laurent Montel committed
209
    if (!fp || list.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
210
211
212
213
214
215
216
217
        return;
    }

    QTextStream t(fp);
    t.setCodec("ISO 8859-1");

    typedef QMap<int, const KContacts::Addressee *> AddresseeMap;
    AddresseeMap addresseeMap;
Laurent Montel's avatar
Laurent Montel committed
218
    const KContacts::Addressee *addressee = nullptr;
Laurent Montel's avatar
Laurent Montel committed
219
220
221

    t << "AB_ADDRESSES:\n";
    t << "Address_id,Nickname,Firstname,Lastname,Title,Birthday,Comments,"
Laurent Montel's avatar
Laurent Montel committed
222
         "Change_date,Status,Address_link_id,Categories\n";
Laurent Montel's avatar
Laurent Montel committed
223

Laurent Montel's avatar
Laurent Montel committed
224
    QStringList categoryMap;
Laurent Montel's avatar
Laurent Montel committed
225
226
227
228
229
    categoryMap.append(assignedCategoriesSorted(list));

    int addresseeId = 0;
    const QChar DELIM(QLatin1Char('#'));
    for (KContacts::AddresseeList::ConstIterator it = list.begin();
Laurent Montel's avatar
Laurent Montel committed
230
         it != list.end(); ++it) {
Laurent Montel's avatar
Laurent Montel committed
231
232
233
234
235
236
237
238
239
        addressee = &(*it);
        if (addressee->isEmpty()) {
            continue;
        }
        addresseeMap[ ++addresseeId ] = addressee;

        // Assign categories as bitfield
        const QStringList categories = addressee->categories();
        long int category = 0;
Laurent Montel's avatar
Laurent Montel committed
240
        if (!categories.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
241
242
            const int categoriesCount(categories.count());
            for (int i = 0; i < categoriesCount; ++i) {
Laurent Montel's avatar
Laurent Montel committed
243
244
245
                const QString cat = categories[i];
                if (categoryMap.contains(cat)) {
                    category |= 1 << categoryMap.indexOf(cat, 0);
Laurent Montel's avatar
Laurent Montel committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
                }
            }
        }

        // GMX sorts by nickname by default - don't leave empty
        QString nickName = addressee->nickName();
        if (nickName.isEmpty()) {
            nickName = addressee->formattedName();
        }

        t << addresseeId << DELIM             // Address_id
          << nickName << DELIM                // Nickname
          << addressee->givenName() << DELIM  // Firstname
          << addressee->familyName() << DELIM // Lastname
          << addressee->prefix() << DELIM     // Title - Note: ->title()
Laurent Montel's avatar
Laurent Montel committed
261
            // refers to the professional title
Laurent Montel's avatar
Laurent Montel committed
262
263
264
265
266
          << dateString(addressee->birthday()) << DELIM     // Birthday
          << addressee->note() /*.replace('\n',"\r\n")*/ << DELIM // Comments
          << dateString(addressee->revision()) << DELIM     // Change_date
          << "1" << DELIM                     // Status
          << DELIM                            // Address_link_id
Laurent Montel's avatar
Laurent Montel committed
267
          << category << QLatin1Char('\n');                // Categories
Laurent Montel's avatar
Laurent Montel committed
268
269
270
271
272
    }

    t << "####\n";
    t << "AB_ADDRESS_RECORDS:\n";
    t << "Address_id,Record_id,Street,Country,Zipcode,City,Phone,Fax,Mobile,"
Laurent Montel's avatar
Laurent Montel committed
273
274
         "Mobile_type,Email,Homepage,Position,Comments,Record_type_id,Record_type,"
         "Company,Department,Change_date,Preferred,Status\n";
Laurent Montel's avatar
Laurent Montel committed
275
276

    addresseeId = 1;
Laurent Montel's avatar
Laurent Montel committed
277
    while ((addressee = addresseeMap[ addresseeId ]) != nullptr) {
Laurent Montel's avatar
Laurent Montel committed
278
279
        const KContacts::PhoneNumber::List cellPhones
            = addressee->phoneNumbers(KContacts::PhoneNumber::Cell);
Laurent Montel's avatar
Laurent Montel committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

        const QStringList emails = addressee->emails();

        for (int recId = 0; recId < 3; ++recId) {
            KContacts::Address address;
            KContacts::PhoneNumber phone, fax, cell;

            // address preference flag:
            // & 1: preferred email address
            // & 4: preferred cell phone
            int prefFlag = 0;

            switch (recId) {
            // Assign address, phone and cellphone, fax if applicable
            case typeHome:
                address = addressee->address(KContacts::Address::Home);
Laurent Montel's avatar
Laurent Montel committed
296
                phone = addressee->phoneNumber(KContacts::PhoneNumber::Home);
Laurent Montel's avatar
Laurent Montel committed
297
                if (!cellPhones.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
298
                    cell = cellPhones.at(0);
Laurent Montel's avatar
Laurent Montel committed
299
300
301
302
303
304
305
                    if (!cell.isEmpty()) {
                        prefFlag |= 4;
                    }
                }
                break;
            case typeWork:
                address = addressee->address(KContacts::Address::Work);
Laurent Montel's avatar
Laurent Montel committed
306
                phone = addressee->phoneNumber(KContacts::PhoneNumber::Work);
Laurent Montel's avatar
Laurent Montel committed
307
                if (cellPhones.count() >= 2) {
Laurent Montel's avatar
Laurent Montel committed
308
                    cell = cellPhones.at(1);
Laurent Montel's avatar
Laurent Montel committed
309
310
311
312
313
314
315
316
                }
                fax = addressee->phoneNumber(KContacts::PhoneNumber::Fax);
                break;
            case typeOther:
            default:
                if (addressee->addresses(KContacts::Address::Home).count() > 1) {
                    address = addressee->addresses(KContacts::Address::Home).at(1);
                }
Laurent Montel's avatar
Laurent Montel committed
317
318
                if ((address.isEmpty())
                    && (addressee->addresses(KContacts::Address::Work).count() > 1)) {
Laurent Montel's avatar
Laurent Montel committed
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
                    address = addressee->addresses(KContacts::Address::Work).at(1);
                }
                if (address.isEmpty()) {
                    address = addressee->address(KContacts::Address::Dom);
                }
                if (address.isEmpty()) {
                    address = addressee->address(KContacts::Address::Intl);
                }
                if (address.isEmpty()) {
                    address = addressee->address(KContacts::Address::Postal);
                }
                if (address.isEmpty()) {
                    address = addressee->address(KContacts::Address::Parcel);
                }

                if (addressee->phoneNumbers(KContacts::PhoneNumber::Home).count() > 1) {
                    phone = addressee->phoneNumbers(KContacts::PhoneNumber::Home).at(1);
                }
                if ((phone.isEmpty()) && (addressee->phoneNumbers(
                                              KContacts::PhoneNumber::Work).count() > 1)) {
                    phone = addressee->phoneNumbers(KContacts::PhoneNumber::Work).at(1);
                }
                if (phone.isEmpty()) {
                    phone = addressee->phoneNumber(KContacts::PhoneNumber::Voice);
                }
                if (phone.isEmpty()) {
                    phone = addressee->phoneNumber(KContacts::PhoneNumber::Msg);
                }
                if (phone.isEmpty()) {
                    phone = addressee->phoneNumber(KContacts::PhoneNumber::Isdn);
                }
                if (phone.isEmpty()) {
                    phone = addressee->phoneNumber(KContacts::PhoneNumber::Car);
                }
                if (phone.isEmpty()) {
                    phone = addressee->phoneNumber(KContacts::PhoneNumber::Pager);
                }

                switch (cellPhones.count()) {
                case 0:
                    break;
                case 1:
                case 2:
                    if (!address.isEmpty()) {
                        cell = cellPhones.at(0);
                    }
                    break;
                default:
                    cell = cellPhones.at(2);
                    break;
                }
                break;
            }

            QString email;
            if (emails.count() > recId) {
                email = emails[ recId ];
                if (email == addressee->preferredEmail()) {
                    prefFlag |= 1;
                }
            }

Laurent Montel's avatar
Laurent Montel committed
381
382
            if (!address.isEmpty() || !phone.isEmpty()
                || !cell.isEmpty() || !email.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
                t << addresseeId << DELIM             // Address_id
                  << recId << DELIM                   // Record_id
                  << address.street() << DELIM        // Street
                  << address.country() << DELIM       // Country
                  << address.postalCode() << DELIM    // Zipcode
                  << address.locality() << DELIM      // City
                  << phone.number() << DELIM          // Phone
                  << fax.number() << DELIM            // Fax
                  << cell.number() << DELIM           // Mobile

                  << ((recId == typeWork) ? 0 : 1) << DELIM     // Mobile_type

                  << email << DELIM                   // Email

Laurent Montel's avatar
Laurent Montel committed
397
398
399
                  << ((recId == typeWork)
                    ? addressee->url().url().url()
                    : QString()) << DELIM  // Homepage
Laurent Montel's avatar
Laurent Montel committed
400

Laurent Montel's avatar
Laurent Montel committed
401
402
403
                  << ((recId == typeWork)
                    ? addressee->role()
                    : QString()) << DELIM  // Position
Laurent Montel's avatar
Laurent Montel committed
404

Laurent Montel's avatar
Laurent Montel committed
405
406
407
                  << ((recId == typeHome)
                    ? addressee->custom(QStringLiteral("KADDRESSBOOK"), QStringLiteral("X-SpousesName"))
                    : QString()) << DELIM  // Comments
Laurent Montel's avatar
Laurent Montel committed
408
409
410
411
412

                  << recId << DELIM                   // Record_type_id (0,1,2)

                  << DELIM                            // Record_type

Laurent Montel's avatar
Laurent Montel committed
413
414
415
                  << ((recId == typeWork)
                    ? addressee->organization()
                    : QString()) << DELIM  // Company
Laurent Montel's avatar
Laurent Montel committed
416

Laurent Montel's avatar
Laurent Montel committed
417
418
419
                  << ((recId == typeWork)
                    ? addressee->custom(QStringLiteral("KADDRESSBOOK"), QStringLiteral("X-Department"))
                    : QString()) << DELIM  // Department
Laurent Montel's avatar
Laurent Montel committed
420
421
422
423

                  << dateString(addressee->revision()) << DELIM   // Change_date

                  << prefFlag << DELIM                // Preferred:
Laurent Montel's avatar
Laurent Montel committed
424
425
                    // ( & 1: preferred email,
                    //   & 4: preferred cell phone )
Laurent Montel's avatar
Laurent Montel committed
426
                  << 1 << QLatin1Char('\n');                       // Status (should always be "1")
Laurent Montel's avatar
Laurent Montel committed
427
428
429
430
            }
        }

        ++addresseeId;
Laurent Montel's avatar
Laurent Montel committed
431
    }
Laurent Montel's avatar
Laurent Montel committed
432

Laurent Montel's avatar
Laurent Montel committed
433
434
435
    t << "####" << QLatin1Char('\n');
    t << "AB_CATEGORIES:" << QLatin1Char('\n');
    t << "Category_id,Name,Icon_id" << QLatin1Char('\n');
Laurent Montel's avatar
Laurent Montel committed
436
437
438
439

    //  Write Category List (beware: Category_ID 0 is reserved for none
    //  Interestingly: The index here is an int sequence and does not
    //  correspond to the bit reference used above.
Laurent Montel's avatar
Laurent Montel committed
440
441
    const int categoryCount(categoryMap.size());
    for (int i = 0; i < categoryCount; ++i) {
Laurent Montel's avatar
Laurent Montel committed
442
        t << (i + 1) << DELIM << categoryMap.at(i) << DELIM << 0 << QLatin1Char('\n');
Laurent Montel's avatar
Laurent Montel committed
443
    }
Laurent Montel's avatar
Laurent Montel committed
444
    t << "####" << QLatin1Char('\n');
Laurent Montel's avatar
Laurent Montel committed
445
446
}

Laurent Montel's avatar
Laurent Montel committed
447
448
void GMXImportExportPluginInterface::importGMX()
{
Laurent Montel's avatar
Laurent Montel committed
449
    const QString fileName
Laurent Montel's avatar
Laurent Montel committed
450
        = QFileDialog::getOpenFileName(parentWidget(), QString(), QDir::homePath(), GMX_FILESELECTION_STRING);
Laurent Montel's avatar
Laurent Montel committed
451
452
453
454
455
456
457

    if (fileName.isEmpty()) {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
Laurent Montel's avatar
Laurent Montel committed
458
        const QString msg = i18n("<qt>Unable to open <b>%1</b> for reading.</qt>", fileName);
Laurent Montel's avatar
Laurent Montel committed
459
460
461
462
463
464
465
466
        KMessageBox::error(parentWidget(), msg);
        return;
    }

    QDateTime dt;
    QTextStream gmxStream(&file);
    gmxStream.setCodec("ISO 8859-1");
    QString line, line2;
Laurent Montel's avatar
Laurent Montel committed
467
    line = gmxStream.readLine();
Laurent Montel's avatar
Laurent Montel committed
468
    line2 = gmxStream.readLine();
Laurent Montel's avatar
Laurent Montel committed
469
470
    if (!line.startsWith(QLatin1String("AB_ADDRESSES:"))
        || !line2.startsWith(QLatin1String("Address_id"))) {
Laurent Montel's avatar
Laurent Montel committed
471
472
473
474
475
476
477
        KMessageBox::error(
            parentWidget(),
            i18n("%1 is not a GMX address book file.", fileName));
        return;
    }

    QStringList itemList;
Laurent Montel's avatar
Laurent Montel committed
478
    QMap<QString, QString> categoriesOfAddressee;
Laurent Montel's avatar
Laurent Montel committed
479
480
481
482
483
484
485
486
487
    typedef QMap<QString, KContacts::Addressee *> AddresseeMap;
    AddresseeMap addresseeMap;

    // "Address_id,Nickname,Firstname,Lastname,Title,Birthday,Comments,
    // Change_date,Status,Address_link_id,Categories"
    line = gmxStream.readLine();
    while ((line != QLatin1String("####")) && !gmxStream.atEnd()) {
        // an addressee entry may spread over several lines in the file
        while (1) {
488
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
489
            itemList = line.split(QLatin1Char('#'), QString::KeepEmptyParts);
490
491
492
#else
            itemList = line.split(QLatin1Char('#'), Qt::KeepEmptyParts);
#endif
Laurent Montel's avatar
Laurent Montel committed
493
494
495
496
497
            if (itemList.count() >= 11) {
                break;
            }
            line.append(QLatin1Char('\n'));
            line.append(gmxStream.readLine());
Laurent Montel's avatar
Laurent Montel committed
498
        }
Laurent Montel's avatar
Laurent Montel committed
499
500
501
502
503
504

        // populate the addressee
        KContacts::Addressee *addressee = new KContacts::Addressee;
        addressee->setNickName(itemList.at(1));
        addressee->setGivenName(itemList.at(2));
        addressee->setFamilyName(itemList.at(3));
Laurent Montel's avatar
Laurent Montel committed
505
        addressee->setFormattedName(itemList.at(3) + QStringLiteral(", ") + itemList.at(2));
Laurent Montel's avatar
Laurent Montel committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
        addressee->setPrefix(itemList.at(4));
        if (checkDateTime(itemList.at(5), dt)) {
            addressee->setBirthday(dt);
        }
        addressee->setNote(itemList.at(6));
        if (checkDateTime(itemList.at(7), dt)) {
            addressee->setRevision(dt);
        }
        // addressee->setStatus( itemList[8] ); Status
        // addressee->xxx( itemList[9] ); Address_link_id
        categoriesOfAddressee[ itemList[0] ] = itemList[10];
        addresseeMap[ itemList[0] ] = addressee;

        line = gmxStream.readLine();
    }

    // now read the address records
Laurent Montel's avatar
Laurent Montel committed
523
    line = gmxStream.readLine();
Laurent Montel's avatar
Laurent Montel committed
524
    if (!line.startsWith(QLatin1String("AB_ADDRESS_RECORDS:"))) {
Laurent Montel's avatar
Laurent Montel committed
525
        qCWarning(KADDRESSBOOK_IMPORTEXPORT_GMX_LOG) << "Could not find address records!";
Laurent Montel's avatar
Laurent Montel committed
526
527
528
529
530
531
532
533
        return;
    }
    // Address_id,Record_id,Street,Country,Zipcode,City,Phone,Fax,Mobile,
    // Mobile_type,Email,Homepage,Position,Comments,Record_type_id,Record_type,
    // Company,Department,Change_date,Preferred,Status
    line = gmxStream.readLine();
    line = gmxStream.readLine();

Laurent Montel's avatar
Laurent Montel committed
534
    while (!line.startsWith(QLatin1String("####")) && !gmxStream.atEnd()) {
Laurent Montel's avatar
Laurent Montel committed
535
536
        // an address entry may spread over several lines in the file
        while (1) {
537
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
538
            itemList = line.split(QLatin1Char('#'), QString::KeepEmptyParts);
539
540
541
#else
            itemList = line.split(QLatin1Char('#'), Qt::KeepEmptyParts);
#endif
Laurent Montel's avatar
Laurent Montel committed
542
543
544
545
546
            if (itemList.count() >= 21) {
                break;
            }
            line.append(QLatin1Char('\n'));
            line.append(gmxStream.readLine());
Laurent Montel's avatar
Laurent Montel committed
547
        }
Laurent Montel's avatar
Laurent Montel committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618

        KContacts::Addressee *addressee = addresseeMap[ itemList[0] ];
        if (addressee) {
            // itemList[1] = Record_id (numbered item, ignore here)
            int recordTypeId = itemList[14].toInt();
            KContacts::Address::Type addressType;
            KContacts::PhoneNumber::Type phoneType;
            switch (recordTypeId) {
            case typeHome:
                addressType = KContacts::Address::Home;
                phoneType = KContacts::PhoneNumber::Home;
                break;
            case typeWork:
                addressType = KContacts::Address::Work;
                phoneType = KContacts::PhoneNumber::Work;
                break;
            case typeOther:
            default:
                addressType = KContacts::Address::Intl;
                phoneType = KContacts::PhoneNumber::Voice;
                break;
            }
            KContacts::Address address = addressee->address(addressType);
            address.setStreet(itemList[2]);
            address.setCountry(itemList[3]);
            address.setPostalCode(itemList[4]);
            address.setLocality(itemList[5]);
            if (!itemList[6].isEmpty()) {
                addressee->insertPhoneNumber(
                    KContacts::PhoneNumber(itemList[6], phoneType));
            }
            if (!itemList[7].isEmpty()) {
                addressee->insertPhoneNumber(
                    KContacts::PhoneNumber(itemList[7], KContacts::PhoneNumber::Fax));
            }
            KContacts::PhoneNumber::Type cellType = KContacts::PhoneNumber::Cell;
            // itemList[9]=Mobile_type // always 0 or -1(default phone).
            // if ( itemList[19].toInt() & 4 ) cellType |= KContacts::PhoneNumber::Pref;
            // don't do the above to avoid duplicate mobile numbers
            if (!itemList[8].isEmpty()) {
                addressee->insertPhoneNumber(KContacts::PhoneNumber(itemList[8], cellType));
            }
            bool preferred = false;
            if (itemList[19].toInt() & 1) {
                preferred = true;
            }
            addressee->insertEmail(itemList[10], preferred);
            if (!itemList[11].isEmpty()) {
                KContacts::ResourceLocatorUrl url;
                url.setUrl(QUrl(itemList[11]));
                addressee->setUrl(url);
            }
            if (!itemList[12].isEmpty()) {
                addressee->setRole(itemList[12]);
            }
            // itemList[13]=Comments
            // itemList[14]=Record_type_id (0,1,2) - see above
            // itemList[15]=Record_type (name of this additional record entry)
            if (!itemList[16].isEmpty()) {
                addressee->setOrganization(itemList[16]);   // Company
            }
            if (!itemList[17].isEmpty()) {
                addressee->insertCustom(QStringLiteral("KADDRESSBOOK"), QStringLiteral("X-Department"), itemList[17]);   // Department
            }
            if (checkDateTime(itemList[18], dt)) {
                addressee->setRevision(dt);   // Change_date
            }
            // itemList[19]=Preferred (see above)
            // itemList[20]=Status (should always be "1")
            addressee->insertAddress(address);
        } else {
Laurent Montel's avatar
Laurent Montel committed
619
            qCWarning(KADDRESSBOOK_IMPORTEXPORT_GMX_LOG) << "unresolved line:" << line;
Laurent Montel's avatar
Laurent Montel committed
620
621
622
623
624
625
626
627
        }
        line = gmxStream.readLine();
    }

    // extract the categories from the list of addressees of the file to import
    QStringList usedCategoryList;
    line = gmxStream.readLine();
    line2 = gmxStream.readLine();
Laurent Montel's avatar
Laurent Montel committed
628
629
    if (!line.startsWith(QLatin1String("AB_CATEGORIES:"))
        || !line2.startsWith(QLatin1String("Category_id"))) {
Laurent Montel's avatar
Laurent Montel committed
630
        qCWarning(KADDRESSBOOK_IMPORTEXPORT_GMX_LOG) << "Could not find category records!";
Laurent Montel's avatar
Laurent Montel committed
631
    } else {
Laurent Montel's avatar
Laurent Montel committed
632
        while (!line.startsWith(QLatin1String("####"))
Laurent Montel's avatar
Laurent Montel committed
633
               && !gmxStream.atEnd()) {
Laurent Montel's avatar
Laurent Montel committed
634
635
            // a category should not spread over multiple lines, but just in case
            while (1) {
636
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
637
                itemList = line.split(QLatin1Char('#'), QString::KeepEmptyParts);
638
639
640
#else
                itemList = line.split(QLatin1Char('#'), Qt::KeepEmptyParts);
#endif
Laurent Montel's avatar
Laurent Montel committed
641
642
643
644
645
                if (itemList.count() >= 3) {
                    break;
                }
                line.append(QLatin1Char('\n'));
                line.append(gmxStream.readLine());
Laurent Montel's avatar
Laurent Montel committed
646
            }
Laurent Montel's avatar
Laurent Montel committed
647
648
            usedCategoryList.append(itemList[1]);
            line = gmxStream.readLine();
Laurent Montel's avatar
Laurent Montel committed
649
        }
Laurent Montel's avatar
Laurent Montel committed
650
651
652
653
654
    }
    KContacts::Addressee::List addresseeList;

    // now add the addresses to addresseeList
    for (AddresseeMap::Iterator addresseeIt = addresseeMap.begin();
Laurent Montel's avatar
Laurent Montel committed
655
         addresseeIt != addresseeMap.end(); ++addresseeIt) {
Laurent Montel's avatar
Laurent Montel committed
656
657
        KContacts::Addressee *addressee = addresseeIt.value();
        // Add categories
658
        // categories is a bitfield with max 31 defined categories
Laurent Montel's avatar
Laurent Montel committed
659
660
661
662
663
664
665
        int categories = categoriesOfAddressee[ addresseeIt.key() ].toInt();
        for (int i = 32; i >= 0; --i) {
            // convert category index to bitfield value for comparison
            int catBit = 1 << i;
            if (catBit > categories) {
                continue; // current index unassigned
            }
Laurent Montel's avatar
Laurent Montel committed
666
            if (catBit & categories && usedCategoryList.count() > i) {
Laurent Montel's avatar
Laurent Montel committed
667
668
669
670
671
672
673
674
                addressee->insertCategory(usedCategoryList[i]);
            }
        }
        addresseeList.append(*addressee);
        delete addressee;
    }

    file.close();
675
    KAddressBookImportExport::KAddressBookImportExportContactList contactList;
Laurent Montel's avatar
Laurent Montel committed
676
677
678
679
680
681
    contactList.setAddressList(addresseeList);

    ImportExportEngine *engine = new ImportExportEngine(this);
    engine->setContactList(contactList);
    engine->setDefaultAddressBook(defaultCollection());
    engine->importContacts();
Laurent Montel's avatar
Laurent Montel committed
682
}
Laurent Montel's avatar
Laurent Montel committed
683
684
685

bool GMXImportExportPluginInterface::canImportFileType(const QUrl &url)
{
Laurent Montel's avatar
Laurent Montel committed
686
    return url.path().endsWith(QLatin1String(".gmx"));
Laurent Montel's avatar
Laurent Montel committed
687
}