File: cdsimcontroller.cpp

package info (click to toggle)
contactsd 1.4.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,392 kB
  • sloc: cpp: 8,862; ansic: 3,793; sh: 361; xml: 75; python: 22; makefile: 13
file content (825 lines) | stat: -rw-r--r-- 28,304 bytes parent folder | download
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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/** This file is part of Contacts daemon
 **
 ** Copyright (c) 2013-2019 Jolla Ltd.
 ** Copyright (c) 2020 Open Mobile Platform LLC.
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser General Public License
 ** version 2.1 as published by the Free Software Foundation and appearing in the
 ** file LICENSE.LGPL included in the packaging of this file.  Please review the
 ** following information to ensure the GNU Lesser General Public License version
 ** 2.1 requirements will be met:
 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **/

#include "cdsimcontroller.h"
#include "cdsimplugin.h"
#include "debug.h"

#include <qtcontacts-extensions.h>
#include <qtcontacts-extensions_manager_impl.h>
#include <contactmanagerengine.h>
#include <QContactDeactivated>
#include <QContactStatusFlags>

#include <QContactDetailFilter>
#include <QContactIntersectionFilter>
#include <QContactCollectionFilter>
#include <QContactNickname>
#include <QContactPhoneNumber>
#include <QContactTag>

#include <QVersitContactImporter>

using namespace Contactsd;

namespace {

const QString CollectionKeyModemPath = QStringLiteral("ModemPath");
const QString CollectionKeyModemIdentifier = QStringLiteral("ModemIdentifier");

QMap<QString, QString> contactManagerParameters()
{
    QMap<QString, QString> rv;
    rv.insert(QStringLiteral("mergePresenceChanges"), QStringLiteral("false"));
    return rv;
}

}

CDSimModemData::CDSimModemData(CDSimController *controller, const QString &modemPath)
    : QObject(controller)
    , m_modemPath(modemPath)
#ifdef HAS_MLITE
    , m_voicemailConf(0)
#endif // HAS_MLITE
    , m_ready(false)
    , m_retries(0)
{
    connect(&m_simManager, SIGNAL(presenceChanged(bool)), SLOT(simStateChanged()));
    connect(&m_simManager, SIGNAL(cardIdentifierChanged(QString)), SLOT(simStateChanged()));

    connect(&m_phonebook, SIGNAL(importReady(QString)), SLOT(vcardDataAvailable(QString)));
    connect(&m_phonebook, SIGNAL(importFailed()), SLOT(vcardReadFailed()));

    // Resync the contacts list whenever the phonebook availability changes
    connect(&m_phonebook, SIGNAL(validChanged(bool)), SLOT(phonebookValidChanged(bool)));

    connect(&m_contactReader, SIGNAL(stateChanged(QVersitReader::State)), SLOT(readerStateChanged(QVersitReader::State)));

    connect(&m_messageWaiting, SIGNAL(voicemailMailboxNumberChanged(QString)), SLOT(voicemailConfigurationChanged()));

    // Don't activate ofono objects in test mode
    if (controller->m_active) {
        // Start reading the SIM contacts
        m_simManager.setModemPath(m_modemPath);
        m_simInfo.setModemPath(m_modemPath);
        m_phonebook.setModemPath(m_modemPath);
        m_messageWaiting.setModemPath(m_modemPath);
    }
}

CDSimModemData::~CDSimModemData()
{
#ifdef HAS_MLITE
    delete m_voicemailConf;
#endif // HAS_MLITE
}

CDSimController *CDSimModemData::controller() const
{
    return qobject_cast<CDSimController *>(parent());
}

QContactManager &CDSimModemData::manager() const
{
    return controller()->contactManager();
}

QString CDSimModemData::modemIdentifier() const
{
    if (controller()->m_active) {
        return m_simManager.cardIdentifier();
    }
    return m_modemPath;
}

QString CDSimModemData::modemPath() const
{
    return m_modemPath;
}

QContactCollection CDSimModemData::contactCollection() const
{
    return m_collection;
}

QList<QContact> CDSimModemData::fetchContacts() const
{
    QContactCollectionFilter filter;
    filter.setCollectionId(m_collection.id());

    QContactFetchHint hint;
    hint.setOptimizationHints(QContactFetchHint::NoRelationships | QContactFetchHint::NoActionPreferences | QContactFetchHint::NoBinaryBlobs);

    return manager().contacts(filter, QList<QContactSortOrder>(), hint);
}

bool CDSimModemData::ready() const
{
    return m_ready;
}

void CDSimModemData::setReady(bool ready)
{
    if (m_ready != ready) {
        m_ready = ready;
        emit readyChanged(m_ready);

        if (m_ready) {
            initCollection();
            updateVoicemailConfiguration();

            if (m_phonebook.isValid()) {
                performTransientImport();
            }
        }
    }
}

void CDSimModemData::updateBusy()
{
    controller()->updateBusy();
}

void CDSimModemData::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_retryTimer.timerId()) {
        m_retryTimer.stop();

        if (m_ready) {
            performTransientImport();
        }
    }
}


CDSimController::CDSimController(QObject *parent, bool active)
    : QObject(parent)
    , m_manager(QStringLiteral("org.nemomobile.contacts.sqlite"), contactManagerParameters())
    , m_transientImport(true)
    , m_busy(false)
    , m_active(active)
#ifdef HAS_MLITE
    , m_transientImportConf(QString::fromLatin1("/org/nemomobile/contacts/sim/transient_import"))
#endif // HAS_MLITE
{
#ifdef HAS_MLITE
    QVariant transientImport = m_transientImportConf.value();
    if (transientImport.isValid())
        m_transientImport = (transientImport.toInt() == 1);

    connect(&m_transientImportConf, SIGNAL(valueChanged()), this, SLOT(transientImportConfigurationChanged()));
#endif // HAS_MLITE
}

CDSimController::~CDSimController()
{
}

static QContactFilter deactivatedFilter()
{
    return QContactStatusFlags::matchFlag(QContactStatusFlags::IsDeactivated, QContactFilter::MatchContains);
}

QContactManager &CDSimController::contactManager()
{
    return m_manager;
}

QContactCollection CDSimController::contactCollection(const QString &modemPath) const
{
    for (auto it = m_modems.constBegin(); it != m_modems.constEnd(); ++it) {
        CDSimModemData *data = it.value();
        if (data->modemPath() == modemPath) {
            return data->contactCollection();
        }
    }

    return QContactCollection();
}

int CDSimController::modemIndex(const QString &modemPath) const
{
    return m_availableModems.indexOf(modemPath);
}

void CDSimController::setModemPaths(const QStringList &paths)
{
    qWarning() << "Managing SIM contacts for modem paths:" << paths;

    m_availableModems = paths;

    QMap<QString, CDSimModemData *>::iterator it = m_modems.begin();
    while (it != m_modems.end()) {
        if (paths.contains(it.key())) {
            ++it;
        } else {
            // This modem is no longer active; remove it
            delete it.value();
            it = m_modems.erase(it);
        }
    }

    QSet<QString> absentModemPaths;

    foreach (const QString &path, paths) {
        CDSimModemData *modemData = m_modems.value(path);
        if (!modemData) {
            modemData = new CDSimModemData(this, path);
            connect(modemData, SIGNAL(readyChanged(bool)), SLOT(modemReadyChanged(bool)));
            m_modems.insert(path, modemData);
        }

        if (!modemData->ready()) {
            absentModemPaths.insert(path);
        }
    }

    if (absentModemPaths.isEmpty()) {
        // Remove any SIM contacts that don't originate from our current modems
        removeObsoleteSimCollections();
    } else {
        // Check for obsolete contacts after all modems are ready
        m_absentModemPaths = absentModemPaths;
        m_readyTimer.start(30 * 1000, this);
    }
}

bool CDSimController::busy() const
{
    return m_busy;
}

void CDSimController::updateBusy()
{
    bool busy = false;
    QMap<QString, CDSimModemData *>::const_iterator mit = m_modems.constBegin(), mend = m_modems.constEnd();
    for ( ; !busy && mit != mend; ++mit) {
        busy |= ((*mit)->m_phonebook.importing() || (*mit)->m_contactReader.state() == QVersitReader::ActiveState);
    }

    if (m_busy != busy) {
        m_busy = busy;
        emit busyChanged(m_busy);
    }
}

void CDSimController::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_readyTimer.timerId()) {
        m_readyTimer.stop();

        if (!m_absentModemPaths.isEmpty()) {
            // Stop waiting for these modems to report presence
            m_absentModemPaths.clear();
            removeObsoleteSimCollections();
        }
    }
}

void CDSimModemData::performTransientImport()
{
    if (modemIdentifier().isEmpty()) {
        qWarning() << "No identifier available for modem:" << m_simManager.modemPath();
        return;
    }

    if (m_phonebook.isValid() && controller()->m_transientImport) {
        // Read all contacts from the SIM
        m_phonebook.beginImport();
    } else {
        m_simContacts.clear();
        deactivateAllSimContacts();
    }

    updateBusy();
}

#ifdef HAS_MLITE
void CDSimController::transientImportConfigurationChanged()
{
    bool importEnabled(true);

    QVariant transientImport = m_transientImportConf.value();
    if (transientImport.isValid())
        importEnabled = (transientImport.toInt() == 1);

    if (m_transientImport != importEnabled) {
        m_transientImport = importEnabled;

        QMap<QString, CDSimModemData *>::const_iterator mit = m_modems.constBegin(), mend = m_modems.constEnd();
        for ( ; mit != mend; ++mit) {
            (*mit)->performTransientImport();
        }
    }
}
#endif // HAS_MLITE

void CDSimController::modemReadyChanged(bool ready)
{
    CDSimModemData *modem = qobject_cast<CDSimModemData *>(sender());
    if (ready && m_absentModemPaths.contains(modem->m_simManager.modemPath())) {
        m_absentModemPaths.remove(modem->m_simManager.modemPath());
        if (m_absentModemPaths.isEmpty()) {
            m_readyTimer.stop();

            // Remove any SIM contacts that don't originate from our current modems
            removeObsoleteSimCollections();
        }
    }
}

void CDSimModemData::simStateChanged()
{
    setReady(m_simManager.present() && !m_simManager.cardIdentifier().isEmpty());
}

void CDSimModemData::phonebookValidChanged(bool)
{
    if (m_ready) {
        performTransientImport();
    }
}

void CDSimModemData::vcardDataAvailable(const QString &vcardData)
{
    // Create contact records from the SIM VCard data
    m_simContacts.clear();
    m_contactReader.setData(vcardData.toUtf8());
    m_contactReader.startReading();
    updateBusy();

    m_retries = 0;
}

void CDSimModemData::vcardReadFailed()
{
    qWarning() << "Unable to read VCard data from SIM:" << m_phonebook.modemPath();
    updateBusy();

    const int maxRetries = 5;
    if (m_retries < maxRetries) {
        ++m_retries;

        // Wait a short period before trying again; the phonebook often reports
        // a failure to read contact data on attempts early after boot
        m_retryTimer.start(10 * 1000, this);
    }
}

void CDSimModemData::readerStateChanged(QVersitReader::State state)
{
    if (state != QVersitReader::FinishedState)
        return;

    QList<QVersitDocument> results = m_contactReader.results();

    if (results.isEmpty()) {
        m_simContacts.clear();
        removeAllSimContacts();
    } else {
        QVersitContactImporter importer;
        importer.importDocuments(results);
        m_simContacts = importer.contacts();
        if (m_simContacts.isEmpty()) {
            removeAllSimContacts();
        } else {
            // import or remove contacts from local storage as necessary.
            ensureSimContactsPresent();
        }
    }

    updateBusy();
}

void CDSimModemData::deactivateAllSimContacts()
{
    const QList<QContact> contacts = fetchContacts();
    if (contacts.size()) {
        QList<QContact> deactivatedContacts;

        foreach (QContact contact, contacts) {
            QContactDeactivated deactivated;
            contact.saveDetail(&deactivated);
            deactivatedContacts.append(contact);
        }

        if (!manager().saveContacts(&deactivatedContacts)) {
            qWarning() << "Error deactivating sim contacts";
        }
    }
}

void CDSimModemData::removeAllSimContacts()
{
    if (m_collection.id().isNull()) {
        return;
    }

    QContactCollectionFilter collectionFilter;
    collectionFilter.setCollectionId(m_collection.id());

    const QList<QContactId> contactIds = manager().contactIds(collectionFilter, QList<QContactSortOrder>());
    if (contactIds.count()) {
        if (manager().removeContacts(contactIds)) {
            qDebug() << "Removed sim contacts for modem" << m_modemPath;
        } else {
            qWarning() << "Unable to remove sim contacts for modem" << m_modemPath;
        }
    }
}

void CDSimModemData::ensureSimContactsPresent()
{
    // Ensure all contacts from the SIM are present in the store
    QContactFetchHint hint;
    hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactNickname::Type << QContactPhoneNumber::Type);
    hint.setOptimizationHints(QContactFetchHint::NoRelationships | QContactFetchHint::NoActionPreferences | QContactFetchHint::NoBinaryBlobs);

    QContactCollectionFilter collectionFilter;
    collectionFilter.setCollectionId(m_collection.id());

    QList<QContact> storedSimContacts = manager().contacts(collectionFilter, QList<QContactSortOrder>(), hint);

    // Also find any deactivated SIM contacts
    storedSimContacts.append(manager().contacts(collectionFilter & deactivatedFilter(), QList<QContactSortOrder>(), hint));

    QMap<QString, QContact> existingContacts;
    foreach (const QContact &contact, storedSimContacts) {
        // Identify imported SIM contacts by their nickname record
        const QString nickname(contact.detail<QContactNickname>().nickname().trimmed());
        existingContacts.insert(nickname, contact);
    }

    // coalesce SIM contacts with the same display label.
    QList<QContact> coalescedSimContacts;
    foreach (const QContact &simContact, m_simContacts) {
        const QContactDisplayLabel &displayLabel = simContact.detail<QContactDisplayLabel>();
        const QList<QContactPhoneNumber> &phoneNumbers = simContact.details<QContactPhoneNumber>();

        // search for a pre-existing match in the coalesced list.
        bool coalescedContactFound = false;
        for (int i = 0; i < coalescedSimContacts.size(); ++i) {
            QContact coalescedContact = coalescedSimContacts.at(i);
            if (coalescedContact.detail<QContactDisplayLabel>().label().trimmed() == displayLabel.label().trimmed()) {
                // found a match.  Coalesce the phone numbers and update the contact in the list.
                QList<QContactPhoneNumber> coalescedPhoneNumbers = coalescedContact.details<QContactPhoneNumber>();
                foreach (QContactPhoneNumber phn, phoneNumbers) {
                    // check to see if the coalesced phone numbers list contains this number
                    bool coalescedNumberFound = false;
                    foreach (const QContactPhoneNumber &cphn, coalescedPhoneNumbers) {
                        if (phn.number() == cphn.number()
                                && phn.contexts() == cphn.contexts()
                                && phn.subTypes() == cphn.subTypes()) {
                            // already exists in the coalesced contact, no need to add it.
                            coalescedNumberFound = true;
                            break;
                        }
                    }

                    // if not, add the number to the coalesced contact and to the coalesced list
                    if (!coalescedNumberFound) {
                        coalescedContact.saveDetail(&phn);
                        coalescedPhoneNumbers.append(phn);
                    }
                }
                coalescedSimContacts.replace(i, coalescedContact);
                coalescedContactFound = true;
                break;
            }
        }

        // no match? add to list.
        if (!coalescedContactFound) {
            coalescedSimContacts.append(simContact);
        }
    }

    QList<QContact> importContacts;
    foreach (QContact simContact, coalescedSimContacts) {
        // SIM imports have their name in the display label
        QContactDisplayLabel displayLabel = simContact.detail<QContactDisplayLabel>();

        // first, remove any duplicate phone number details from the sim contact
        QList<QContactPhoneNumber> existingSimPhoneNumbers;
        foreach (QContactPhoneNumber phoneNumber, simContact.details<QContactPhoneNumber>()) {
            bool foundDuplicateNumber = false;
            for (int i = 0; i < existingSimPhoneNumbers.size(); ++i) {
                if (existingSimPhoneNumbers.at(i).number() == phoneNumber.number()
                        && existingSimPhoneNumbers.at(i).contexts() == phoneNumber.contexts()
                        && existingSimPhoneNumbers.at(i).subTypes() == phoneNumber.subTypes()) {
                    // an exact duplicate of this number already exists in the sim contact.
                    foundDuplicateNumber = true;
                    simContact.removeDetail(&phoneNumber);
                    break;
                }
            }

            if (!foundDuplicateNumber) {
                existingSimPhoneNumbers.append(phoneNumber);
            }
        }

        // then, determine whether this contact is already represented in the device phonebook
        QMap<QString, QContact>::iterator it = existingContacts.find(displayLabel.label().trimmed());
        if (it != existingContacts.end()) {
            // Ensure this contact has the right phone numbers
            QContact &dbContact(*it);

            QList<QContactPhoneNumber> existingNumbers(dbContact.details<QContactPhoneNumber>());
            bool modified = false;
            foreach (QContactPhoneNumber phoneNumber, simContact.details<QContactPhoneNumber>()) {
                bool foundExistingNumber = false;
                for (int i = 0; i < existingNumbers.size(); ++i) {
                    if (existingNumbers.at(i).number() == phoneNumber.number()
                            && existingNumbers.at(i).contexts() == phoneNumber.contexts()
                            && existingNumbers.at(i).subTypes() == phoneNumber.subTypes()) {
                        // this number was not modified.  We don't need to change it.
                        foundExistingNumber = true;
                        existingNumbers.removeAt(i);
                        break;
                    }
                }

                if (!foundExistingNumber) {
                    // this number is new, or modified.  We need to change it.
                    dbContact.saveDetail(&phoneNumber);
                    modified = true;
                }
            }

            // Remove any obsolete numbers
            foreach (QContactPhoneNumber phoneNumber, existingNumbers) {
                dbContact.removeDetail(&phoneNumber);
                modified = true;
            }

            // Reactivate this contact if necessary
            if (!dbContact.details<QContactDeactivated>().isEmpty()) {
                QContactDeactivated deactivated = dbContact.detail<QContactDeactivated>();
                dbContact.removeDetail(&deactivated);
                modified = true;
            }

            if (modified) {
                // Add the modified contact to the import set
                importContacts.append(dbContact);
            }
            existingContacts.erase(it);
        } else {
            // We need to import this contact
            simContact.setCollectionId(m_collection.id());

            // Convert the display label to a nickname; display label is managed by the backend
            QContactNickname nickname = simContact.detail<QContactNickname>();
            nickname.setNickname(displayLabel.label().trimmed());
            simContact.saveDetail(&nickname);
            simContact.removeDetail(&displayLabel);

            importContacts.append(simContact);
        }
    }

    if (!importContacts.isEmpty()) {
        // Import any contacts which were modified or are not currently present
        if (!manager().saveContacts(&importContacts)) {
            qWarning() << "Error while saving imported sim contacts";
        }
    }

    if (!existingContacts.isEmpty()) {
        // Remove any imported contacts no longer on the SIM
        QList<QContactId> obsoleteIds;
        foreach (const QContact &contact, existingContacts.values()) {
            obsoleteIds.append(contact.id());
        }

        if (!manager().removeContacts(obsoleteIds)) {
            qWarning() << "Error while removing obsolete sim contacts";
        }
    }
}

void CDSimModemData::voicemailConfigurationChanged()
{
#ifdef HAS_MLITE
    if (!m_voicemailConf || !m_simManager.present()) {
        // Wait until SIM is present
        return;
    }

    const QString voicemailTarget(QString::fromLatin1("voicemail"));

    QContactCollectionFilter collectionFilter;
    collectionFilter.setCollectionId(m_collection.id());

    QContactIntersectionFilter filter;
    filter << collectionFilter;
    filter << QContactTag::match(voicemailTarget);

    QContact voicemailContact;
    for (const QContact &contact : manager().contacts(filter)) {
        voicemailContact = contact;
        break;
    }

    // If there is a manually configured number, prefer that
    QString voicemailNumber(m_voicemailConf->value().toString());
    if (voicemailNumber.isEmpty()) {
        // Otherwise use the number provided for message waiting
        voicemailNumber = m_messageWaiting.voicemailMailboxNumber();
    }

    if (voicemailNumber.isEmpty()) {
        // Remove the voicemail contact if present
        if (!voicemailContact.id().isNull()) {
            if (!manager().removeContact(voicemailContact.id())) {
                qWarning() << "Unable to remove voicemail contact";
            }
        }
    } else {
        // Add/update the voicemail contact if necessary
        QContactPhoneNumber number = voicemailContact.detail<QContactPhoneNumber>();
        if (number.number() == voicemailNumber) {
            // Nothing to change
            return;
        }

        // Update the number
        number.setNumber(voicemailNumber);
        voicemailContact.saveDetail(&number);

        QContactNickname nickname = voicemailContact.detail<QContactNickname>();
        if (nickname.isEmpty()) {
            //: Name for the contact representing the voicemail mailbox
            //% "Voicemail System"
            QString name(qtTrId("qtn_sim_voicemail_contact"));

            const QString simName(m_simInfo.serviceProviderName());
            if (!simName.isEmpty()) {
                name.append(QString(QStringLiteral(" (%1)")).arg(simName));
            }

            nickname.setNickname(name);
            voicemailContact.saveDetail(&nickname);
        }

        const QList<QContactTag> tags = voicemailContact.details<QContactTag>();
        bool foundTag = false;
        for (const QContactTag &tag : tags) {
            if (tag.tag() == voicemailTarget) {
                foundTag = true;
            }
        }
        if (!foundTag) {
            QContactTag tag;
            tag.setTag(voicemailTarget);
            voicemailContact.saveDetail(&tag);
        }

        voicemailContact.setCollectionId(m_collection.id());

        if (!manager().saveContact(&voicemailContact)) {
            qWarning() << "Unable to save voicemail contact";
        }
    }
#endif // HAS_MLITE
}

void CDSimModemData::updateVoicemailConfiguration()
{
#ifdef HAS_MLITE
    QString variablePath(QString::fromLatin1("/sailfish/voicecall/voice_mailbox/"));
    variablePath.append(modemIdentifier());

    if (!m_voicemailConf || m_voicemailConf->key() != variablePath) {
        delete m_voicemailConf;
        m_voicemailConf = new MGConfItem(variablePath);
        connect(m_voicemailConf, SIGNAL(valueChanged()), this, SLOT(voicemailConfigurationChanged()));

        voicemailConfigurationChanged();
    }
#endif // HAS_MLITE
}

void CDSimController::removeObsoleteSimCollections()
{
    QList<QContactCollectionId> obsoleteCollectionIds;

    const QList<QContactCollection> collections = contactManager().collections();

    QSet<QString> currentModemPaths;
    for (CDSimModemData *modem : m_modems.values()) {
        currentModemPaths.insert(modem->modemPath());
    }

    QSet<QString> matchedModemPaths;
    for (const QContactCollection &collection : collections) {
        const QString modemPath = collection.extendedMetaData(CollectionKeyModemPath).toString();
        if (modemPath.isEmpty()) {
            continue;
        }

        if (matchedModemPaths.contains(modemPath)) {
            obsoleteCollectionIds.append(collection.id());
        } else {
            if (currentModemPaths.contains(modemPath)) {
                matchedModemPaths.insert(modemPath);
            } else {
                obsoleteCollectionIds.append(collection.id());
            }
        }
    }

    if (!obsoleteCollectionIds.isEmpty()
            && !CDSimModemData::removeCollections(&contactManager(), obsoleteCollectionIds)) {
        qWarning() << "Error removing sim contacts for collections:" << obsoleteCollectionIds;
    }
}

void CDSimModemData::initCollection()
{
    const int modemIndex = controller()->modemIndex(m_modemPath);
    QString icon;
    if (modemIndex == 0) {
        icon = QStringLiteral("image://theme/icon-m-sim-1");
    } else if (modemIndex == 1) {
        icon = QStringLiteral("image://theme/icon-m-sim-2");
    }

    QContactCollection collection;
    collection.setMetaData(QContactCollection::KeyName, QStringLiteral("SIM"));
    collection.setMetaData(QContactCollection::KeyDescription, QStringLiteral("Contacts stored on SIM card"));
    collection.setMetaData(QContactCollection::KeyColor, QStringLiteral("green"));
    collection.setMetaData(QContactCollection::KeySecondaryColor, QStringLiteral("lightgreen"));
    collection.setMetaData(QContactCollection::KeyImage, icon);
    collection.setExtendedMetaData(COLLECTION_EXTENDEDMETADATA_KEY_APPLICATIONNAME, qApp->applicationName());
    collection.setExtendedMetaData(COLLECTION_EXTENDEDMETADATA_KEY_READONLY, true);
    collection.setExtendedMetaData(CollectionKeyModemPath, m_modemPath);
    collection.setExtendedMetaData(CollectionKeyModemIdentifier, modemIdentifier());

    const QList<QContactCollection> collections = manager().collections();
    for (const QContactCollection &c : collections) {
        const QString modemPath = c.extendedMetaData(CollectionKeyModemPath).toString();
        const QString modemIdentifier = c.extendedMetaData(CollectionKeyModemIdentifier).toString();
        if (modemPath == m_modemPath && modemIdentifier == this->modemIdentifier()) {
            qDebug() << "Found existing SIM collection" << collection.id()
                     << "for path" << m_modemPath
                     << "and modem id" << modemIdentifier;
            m_collection = c;
            break;
        }
    }

    if (m_collection.id().isNull()) {
        if (manager().saveCollection(&collection)) {
            m_collection = collection;
            qDebug() << "Created new SIM collection" << collection.id()
                     << "for path" << m_modemPath
                     << "and modem id" << modemIdentifier();
        } else {
            qWarning() << "Unable to save SIM collection for path" << m_modemPath
                     << "and modem id" << modemIdentifier()
                     << "error is:" << manager().error();
        }
    }
}

bool CDSimModemData::removeCollections(QContactManager *manager, const QList<QContactCollectionId> &collectionIds)
{
    if (collectionIds.isEmpty()) {
        return true;
    }

    QContactManager &m = *manager;
    QtContactsSqliteExtensions::ContactManagerEngine *cme = QtContactsSqliteExtensions::contactManagerEngine(m);
    QContactManager::Error error = QContactManager::NoError;

    bool ret = cme->storeChanges(nullptr,
                                 nullptr,
                                 collectionIds,
                                 QtContactsSqliteExtensions::ContactManagerEngine::PreserveLocalChanges,
                                 true,
                                 &error);
    if (!ret) {
        qWarning() << "Error removing sim contacts from device storage, error was:" << error;
        return false;
    }

    return true;
}

// Instantiate the extension functions
#include <qcontactdeactivated_impl.h>
#include <qcontactstatusflags_impl.h>