~aleteoryx/muditaos

ref: 9eeeb6ae929009c475b2748dc79e3407002876d6 muditaos/module-db/Interface/ContactRecord.cpp -rw-r--r-- 36.2 KiB
9eeeb6ae — Bartek Cichocki [EGD-3502] reworked endpoints and handlers 5 years ago
                                                                                
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
#include "ContactRecord.hpp"
#include "queries/phonebook/QueryContactAdd.hpp"
#include <Utils.hpp>

#include <queries/phonebook/QueryContactGet.hpp>

#include <PhoneNumber.hpp>
#include <NumberHolderMatcher.hpp>

#include <algorithm>
#include <iterator>
#include <optional>
#include <sstream>
#include <vector>

ContactRecordInterface::ContactRecordInterface(ContactsDB *db)
    : contactDB(db), favouritesGroupId(db->groups.favouritesId())
{}

ContactRecordInterface::~ContactRecordInterface()
{}

bool ContactRecordInterface::Add(const ContactRecord &rec)
{
    bool ret = contactDB->contacts.add(ContactsTableRow{
        {.ID = DB_ID_NONE}, .type = rec.contactType, .speedDial = rec.speeddial, .namePrimary = rec.primaryName});

    if (!ret) {
        return false;
    }

    uint32_t contactID = contactDB->getLastInsertRowId();
    LOG_DEBUG("New contact with ID %" PRIu32 " created", contactID);

    ret = contactDB->name.add(ContactsNameTableRow{{.ID = DB_ID_NONE},
                                                   .contactID       = contactID,
                                                   .namePrimary     = rec.primaryName,
                                                   .nameAlternative = rec.alternativeName});

    if (!ret) {
        return false;
    }

    auto contactNameID = contactDB->getLastInsertRowId();

    // build string list of number IDs
    std::string numbersIDs;
    for (auto a : rec.numbers) {
        ret = contactDB->number.add(ContactsNumberTableRow{{.ID = DB_ID_NONE},
                                                           .contactID  = contactID,
                                                           .numberUser = a.number.getEntered().c_str(),
                                                           .numbere164 = a.number.getE164().c_str(),
                                                           .type       = a.numberType});
        if (!ret) {
            return false;
        }

        numbersIDs += std::to_string(contactDB->getLastInsertRowId()) + " ";
    }

    // remove trailing space
    if (!numbersIDs.empty()) {
        numbersIDs.pop_back();
    }

    ret = contactDB->ringtones.add(
        ContactsRingtonesTableRow{.ID = DB_ID_NONE, .contactID = contactID, .assetPath = rec.assetPath});

    if (!ret) {
        return false;
    }

    auto contactRingID = contactDB->getLastInsertRowId();

    ret = contactDB->address.add(ContactsAddressTableRow{
        {.ID = DB_ID_NONE}, .contactID = contactID, .address = rec.address, .note = rec.note, .mail = rec.mail});

    if (!ret) {
        return false;
    }

    auto contactAddressID = contactDB->getLastInsertRowId();

    ret = contactDB->contacts.update(ContactsTableRow{{.ID = contactID},
                                                      .nameID    = contactNameID,
                                                      .numbersID = numbersIDs,
                                                      .ringID    = contactRingID,
                                                      .addressID = contactAddressID,

                                                      .type      = rec.contactType,
                                                      .speedDial = rec.speeddial});
    for (auto group : rec.groups) {
        contactDB->groups.addContactToGroup(contactID, group.ID);
    }

    return ret;
}

bool ContactRecordInterface::BlockByID(uint32_t id, const bool shouldBeBlocked)
{
    return contactDB->contacts.BlockByID(id, shouldBeBlocked);
}

bool ContactRecordInterface::RemoveByID(uint32_t id)
{

    auto contact = contactDB->contacts.getById(id);
    if (contact.ID == 0) {
        return false;
    }

    if (contactDB->name.removeById(contact.nameID) == false) {
        return false;
    }

    if (contactDB->address.removeById(contact.addressID) == false) {
        return false;
    }

    if (contactDB->number.removeById(std::stoul(contact.numbersID)) == false) {
        return false;
    }

    if (contactDB->ringtones.removeById(contact.ringID) == false) {
        return false;
    }

    if (contactDB->contacts.removeById(id) == false) {
        return false;
    }

    return true;
}

std::unique_ptr<db::QueryResult> ContactRecordInterface::runQuery(std::shared_ptr<db::Query> query)
{
    if (query->type != db::Query::Type::Read) {
        LOG_WARN("Received unhandled query type: %lu", static_cast<unsigned long int>(query->type));
        return nullptr;
    }

    auto textFilter = dynamic_cast<const db::query::TextFilter *>(query.get());
    assert(query != nullptr);
    bool searchByNumber = false;
    if (textFilter != nullptr && textFilter->isFilterPresent() && utils::is_number(textFilter->getFilterData())) {
        searchByNumber = true;
        LOG_INFO("Filtering by number: %s", textFilter->getFilterData().c_str());
    }

    if (typeid(*query) == typeid(db::query::ContactGet)) {

        auto readQuery = static_cast<const db::query::ContactGet *>(query.get());
        LOG_DEBUG("Contact read query, filter: \"%s\", offset=%lu, limit=%lu",
                  readQuery->getFilterData().c_str(),
                  static_cast<unsigned long>(readQuery->getOffset()),
                  static_cast<unsigned long>(readQuery->getLimit()));
        auto [limit, offset] = readQuery->getLimitOffset();
        auto matchType       = searchByNumber ? ContactsTable::MatchType::TextNumber : ContactsTable::MatchType::Name;
        uint32_t groupID     = readQuery->getGroupFilterData();
        if (groupID != DB_ID_NONE) {
            matchType = ContactsTable::MatchType::Group;
        }
        else
            groupID = favouritesGroupId;
        LOG_DEBUG("Contact match Type: %lu", static_cast<unsigned long int>(matchType));

        auto ids =
            contactDB->contacts.GetIDsSortedByField(matchType, readQuery->getFilterData(), groupID, limit, offset);

        LOG_DEBUG("Received records: %lu", static_cast<unsigned long int>(ids.size()));

        std::vector<ContactRecord> result(ids.size());
        std::transform(std::begin(ids), std::end(ids), std::begin(result), [this](uint32_t id) { return GetByID(id); });

        auto response = std::make_unique<db::query::ContactGetResult>(result);
        response->setRequestQuery(query);
        return response;
    }
    else if (typeid(*query) == typeid(db::query::ContactGetSize)) {
        auto countQuery = static_cast<const db::query::ContactGetSize *>(query.get());
        LOG_DEBUG("Contact count query, filter: \"%s\"", countQuery->getFilterData().c_str());

        std::size_t count = 0;
        if (!countQuery->isFilterPresent()) {
            uint32_t groupID = countQuery->getGroupFilterData();
            if (groupID != DB_ID_NONE) {
                count = contactDB->contacts
                            .GetIDsSortedByField(ContactsTable::MatchType::Group, countQuery->getFilterData(), groupID)
                            .size();
            }
            else
                count = contactDB->contacts.count();
        }
        else if (searchByNumber) {
            count = contactDB->contacts
                        .GetIDsSortedByField(
                            ContactsTable::MatchType::TextNumber, countQuery->getFilterData(), favouritesGroupId)
                        .size();
        }
        else {
            count = contactDB->name.GetCountByName(countQuery->getFilterData());
        }

        LOG_DEBUG("Contact count query result: %lu", static_cast<unsigned long>(count));

        auto response = std::make_unique<db::query::RecordsSizeQueryResult>(count);
        response->setRequestQuery(query);
        return response;
    }
    else if (typeid(*query) == typeid(db::query::ContactAdd)) {
        auto addQuery = static_cast<const db::query::ContactAdd *>(query.get());
        auto ret      = ContactRecordInterface::Add(addQuery->rec);
        auto response = std::make_unique<db::query::ContactAddResult>(ret);
        response->setRequestQuery(query);
        return response;
    }
    else {
        LOG_ERROR("Unexpected query type.");
        return nullptr;
    }
}

std::vector<std::uint32_t> ContactRecordInterface::splitNumberIDs(const std::string &numberIDs)
{
    std::stringstream source(numberIDs);
    return std::vector<std::uint32_t>(std::istream_iterator<std::uint32_t>(source),
                                      std::istream_iterator<std::uint32_t>());
}

std::string ContactRecordInterface::joinNumberIDs(const std::vector<std::uint32_t> &numberIDs)
{
    std::ostringstream outStream;
    std::ostream_iterator<std::uint32_t> outIterator(outStream, " ");
    std::copy(std::begin(numberIDs), std::end(numberIDs), outIterator);

    return outStream.str();
}

bool ContactRecordInterface::unbindNumber(std::uint32_t contactId, std::uint32_t numberId)
{
    auto contactRecord = contactDB->contacts.getById(contactId);
    if (!contactRecord.isValid()) {
        return false;
    }

    auto numberIDs = splitNumberIDs(contactRecord.numbersID);
    numberIDs.erase(std::remove(std::begin(numberIDs), std::end(numberIDs), numberId), std::end(numberIDs));
    contactRecord.numbersID = joinNumberIDs(numberIDs);

    return contactDB->contacts.update(contactRecord);
}

bool ContactRecordInterface::Update(const ContactRecord &rec)
{
    bool ret;
    ContactsTableRow contact = contactDB->contacts.getById(rec.ID);
    if (!contact.isValid()) {
        return false;
    }

    std::vector<ContactNumberHolder> contactNumberHolders;
    auto numberMatcher                        = buildNumberMatcher(contactNumberHolders);
    std::vector<std::uint32_t> inputNumberIDs = splitNumberIDs(contact.numbersID);
    std::vector<std::uint32_t> outputNumberIDs;
    for (auto number : rec.numbers) {
        auto numberMatch =
            numberMatcher.bestMatch(utils::PhoneNumber(number.number), utils::PhoneNumber::Match::POSSIBLE);
        if (numberMatch == numberMatcher.END) {
            LOG_INFO("Adding number %s", number.number.getEntered().c_str());
            if (!contactDB->number.add(ContactsNumberTableRow{{.ID = DB_ID_NONE},
                                                              .contactID  = contact.ID,
                                                              .numberUser = number.number.getEntered().c_str(),
                                                              .numbere164 = number.number.getE164().c_str(),
                                                              .type       = number.numberType})) {
                LOG_ERROR("Failed to add new number for contact");
                return false;
            }

            outputNumberIDs.push_back(contactDB->getLastInsertRowId());
        }
        else {
            if (auto oldId = numberMatch->getContactID(); oldId != rec.ID) {
                if (!unbindNumber(oldId, numberMatch->getNumberID())) {
                    LOG_ERROR(
                        "Failed to unbind number %" PRIu32 " from contact %" PRIu32, numberMatch->getNumberID(), oldId);
                }

                auto numberRecord      = contactDB->number.getById(numberMatch->getNumberID());
                numberRecord.contactID = rec.ID;

                if (!contactDB->number.update(numberRecord)) {
                    LOG_ERROR("Failed to reassing number %" PRIu32 " to contact %" PRIu32,
                              numberMatch->getNumberID(),
                              rec.ID);
                }
            }
            outputNumberIDs.push_back(numberMatch->getNumberID());
        }
    }

    // cleanup numbers that are missing in new ID list
    for (auto inNumberID : inputNumberIDs) {
        if (std::find(std::begin(outputNumberIDs), std::end(outputNumberIDs), inNumberID) ==
            std::end(outputNumberIDs)) {
            LOG_INFO("Removing obsolete number from table: %" PRIu32, inNumberID);
            if (!contactDB->number.removeById(inNumberID)) {
                LOG_ERROR("Failed to remove number");
                return false;
            }
        }
    }

    // check if speed dial is free to take, unbind if needed
    auto speedDialContacts = GetBySpeedDial(rec.speeddial);
    if (!speedDialContacts->empty()) {
        if (speedDialContacts->size() != 1) {
            LOG_ERROR("Multiple contacts for same speed dial value %s", rec.speeddial.c_str());
        }
        auto oldContact      = contactDB->contacts.getById(speedDialContacts->at(0).ID);
        oldContact.speedDial = "";
        if (!contactDB->contacts.update(oldContact)) {
            LOG_ERROR("Failed to remove speed dial from old contact");
        }
    }

    ret = contactDB->contacts.update(ContactsTableRow{{.ID = contact.ID},
                                                      .nameID          = contact.nameID,
                                                      .numbersID       = joinNumberIDs(outputNumberIDs),
                                                      .ringID          = contact.ringID,
                                                      .addressID       = contact.addressID,
                                                      .type            = rec.contactType,
                                                      .speedDial       = rec.speeddial,
                                                      .namePrimary     = rec.primaryName,
                                                      .nameAlternative = rec.alternativeName});

    if (!ret) {
        LOG_ERROR("Failed to update contact.");
        return false;
    }

    ret = contactDB->name.update(ContactsNameTableRow{{.ID = contact.nameID},
                                                      .contactID       = contact.ID,
                                                      .namePrimary     = rec.primaryName,
                                                      .nameAlternative = rec.alternativeName});

    if (!ret) {
        LOG_ERROR("Failed to update contact name");
        return false;
    }

    ret = contactDB->address.update(ContactsAddressTableRow{{.ID = contact.addressID},
                                                            .contactID = contact.ID,
                                                            .address   = rec.address,
                                                            .note      = rec.note,
                                                            .mail      = rec.mail});

    if (!ret) {
        LOG_ERROR("Failed to update contact address");
        return false;
    }

    ret = contactDB->ringtones.update(ContactsRingtonesTableRow{.contactID = contact.ID, .assetPath = rec.assetPath});

    if (!ret) {
        LOG_ERROR("Failed to update contact ringtone");
        return false;
    }

    contactDB->groups.updateGroups(rec.ID, rec.groups);

    return true;
}

ContactRecord ContactRecordInterface::GetByID(uint32_t id)
{
    ContactRecord rec = ContactRecord();

    auto contact = contactDB->contacts.getById(id);
    if (!contact.isValid()) {
        return rec;
    }

    auto nrs = getNumbers(contact.numbersID);
    if (nrs.size() == 0) {
        LOG_DEBUG("Contact record does not contain any numbers.");
    }
    auto ring = contactDB->ringtones.getById(contact.ringID);
    if (!ring.isValid()) {
        return rec;
    }

    auto address = contactDB->address.getById(contact.addressID);
    if (!address.isValid()) {
        return rec;
    }

    auto name = contactDB->name.getById(contact.nameID);
    if (name.ID == 0) {
        return rec;
    }

    rec.ID              = contact.ID;
    rec.primaryName     = name.namePrimary;
    rec.alternativeName = name.nameAlternative;
    rec.numbers         = nrs;
    rec.contactType     = contact.type;
    rec.address         = address.address;
    rec.note            = address.note;
    rec.mail            = address.mail;
    rec.assetPath       = ring.assetPath;
    rec.speeddial       = contact.speedDial;
    rec.groups          = contactDB->groups.getGroupsForContact(contact.ID);

    return rec;
}

uint32_t ContactRecordInterface::GetCount()
{
    return contactDB->contacts.count();
}

uint32_t ContactRecordInterface::GetCountFavourites()
{
    return contactDB->contacts.countByFieldId("favourites", 1);
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetLimitOffset(uint32_t offset, uint32_t limit)
{
    auto records = std::make_unique<std::vector<ContactRecord>>();

    auto ret = contactDB->name.getLimitOffset(offset, limit);

    for (const auto &w : ret) {

        auto contact = contactDB->contacts.getById(w.ID);
        if (!contact.isValid()) {
            return records;
        }

        auto name = contactDB->name.getById(contact.nameID);
        if (!name.isValid()) {
            return records;
        }

        auto nrs = getNumbers(contact.numbersID);
        if (nrs.size() == 0) {
            LOG_DEBUG("Contact record does not contain any numbers.");
        }

        auto ring = contactDB->ringtones.getById(contact.ringID);
        if (!ring.isValid()) {
            return records;
        }

        auto address = contactDB->address.getById(contact.addressID);
        if (!address.isValid()) {
            return records;
        }

        records->push_back(ContactRecord{{.ID = contact.ID},
                                         .primaryName     = name.namePrimary,
                                         .alternativeName = name.nameAlternative,
                                         .contactType     = contact.type,
                                         .numbers         = nrs,
                                         .address         = address.address,
                                         .note            = address.note,
                                         .mail            = address.mail,
                                         .assetPath       = ring.assetPath,
                                         .speeddial       = contact.speedDial,
                                         .groups          = contactDB->groups.getGroupsForContact(contact.ID)});
    }

    return records;
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetLimitOffsetByField(uint32_t offset,
                                                                                          uint32_t limit,
                                                                                          ContactRecordField field,
                                                                                          const char *str)
{
    auto records = std::make_unique<std::vector<ContactRecord>>();

    switch (field) {
    case ContactRecordField ::PrimaryName: {
        auto ret = contactDB->name.getLimitOffsetByField(offset, limit, ContactNameTableFields::NamePrimary, str);

        for (const auto &record : ret) {

            auto contact = contactDB->contacts.getById(record.contactID);
            if (!contact.isValid()) {
                return records;
            }

            auto nrs = getNumbers(contact.numbersID);
            if (nrs.size() == 0) {
                LOG_DEBUG("Contact record does not contain any numbers.");
            }

            auto ring = contactDB->ringtones.getById(contact.ringID);
            if (!ring.isValid()) {
                return records;
            }

            auto address = contactDB->address.getById(contact.addressID);
            if (!address.isValid()) {
                return records;
            }

            records->push_back(ContactRecord{{.ID = record.ID},
                                             .primaryName     = record.namePrimary,
                                             .alternativeName = record.nameAlternative,
                                             .contactType     = contact.type,
                                             .numbers         = nrs,
                                             .address         = address.address,
                                             .note            = address.note,
                                             .mail            = address.mail,
                                             .assetPath       = ring.assetPath,
                                             .speeddial       = contact.speedDial,
                                             .groups          = contactDB->groups.getGroupsForContact(record.ID)});
        }
    } break;

    case ContactRecordField::NumberUser: {
        auto ret = contactDB->number.getLimitOffsetByField(offset, limit, ContactNumberTableFields ::NumberUser, str);

        for (const auto &record : ret) {

            auto contact = contactDB->contacts.getById(record.contactID);
            if (!contact.isValid()) {
                return records;
            }

            auto nrs = getNumbers(contact.numbersID);
            if (nrs.size() == 0) {
                LOG_DEBUG("Contact record does not contain any numbers.");
            }

            auto name = contactDB->name.getById(contact.nameID);
            if (!name.isValid()) {
                return records;
            }

            auto ring = contactDB->ringtones.getById(contact.ringID);
            if (!ring.isValid()) {
                return records;
            }

            auto address = contactDB->address.getById(contact.addressID);
            if (!address.isValid()) {
                return records;
            }

            records->push_back(ContactRecord{{.ID = record.ID},
                                             .primaryName     = name.namePrimary,
                                             .alternativeName = name.nameAlternative,
                                             .contactType     = contact.type,
                                             .numbers         = nrs,
                                             .address         = address.address,
                                             .note            = address.note,
                                             .mail            = address.mail,
                                             .assetPath       = ring.assetPath,
                                             .speeddial       = contact.speedDial,
                                             .groups          = contactDB->groups.getGroupsForContact(record.ID)

            });
        }
    } break;

    case ContactRecordField::NumberE164: {
        auto ret = contactDB->number.getLimitOffsetByField(offset, limit, ContactNumberTableFields::NumberE164, str);

        for (const auto &record : ret) {

            auto contact = contactDB->contacts.getById(record.contactID);
            if (!contact.isValid()) {
                return records;
            }

            auto nrs = getNumbers(contact.numbersID);
            if (nrs.size() == 0) {
                LOG_DEBUG("Contact record does not contain any numbers.");
            }

            auto name = contactDB->name.getById(contact.nameID);
            if (!name.isValid()) {
                return records;
            }

            auto ring = contactDB->ringtones.getById(contact.ringID);
            if (!ring.isValid()) {
                return records;
            }

            auto address = contactDB->address.getById(contact.addressID);
            if (!address.isValid()) {
                return records;
            }

            records->push_back(ContactRecord{
                {.ID = record.ID},
                .primaryName     = name.namePrimary,
                .alternativeName = name.nameAlternative,
                .contactType     = contact.type,
                .numbers         = nrs,
                .address         = address.address,
                .note            = address.note,
                .mail            = address.mail,
                .assetPath       = ring.assetPath,
                .speeddial       = contact.speedDial,
                .groups          = contactDB->groups.getGroupsForContact(record.ID),

            });
        }
    } break;
    case ContactRecordField::SpeedDial: {
        auto ret = contactDB->contacts.getLimitOffsetByField(0, 1, ContactTableFields::SpeedDial, str);

        for (const auto &w : ret) {

            auto contact = contactDB->contacts.getById(w.ID);
            if (!contact.isValid()) {
                return records;
            }

            auto name = contactDB->name.getById(contact.nameID);
            if (!name.isValid()) {
                return records;
            }

            auto nrs = getNumbers(contact.numbersID);
            if (nrs.size() == 0) {
                LOG_DEBUG("Contact record does not contain any numbers.");
            }

            auto ring = contactDB->ringtones.getById(contact.ringID);
            if (!ring.isValid()) {
                return records;
            }

            auto address = contactDB->address.getById(contact.addressID);
            if (!address.isValid()) {
                return records;
            }

            records->push_back(ContactRecord{{.ID = contact.ID},
                                             .primaryName     = name.namePrimary,
                                             .alternativeName = name.nameAlternative,
                                             .contactType     = contact.type,
                                             .numbers         = nrs,
                                             .address         = address.address,
                                             .note            = address.note,
                                             .mail            = address.mail,
                                             .assetPath       = ring.assetPath,
                                             .speeddial       = contact.speedDial,
                                             .groups          = contactDB->groups.getGroupsForContact(contact.ID)});
        }
    } break;
    case ContactRecordField::Groups: {
        break;
    }
    }

    return records;
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetByName(UTF8 primaryName, UTF8 alternativeName)
{

    auto records = std::make_unique<std::vector<ContactRecord>>();

    auto ret = contactDB->name.GetByName(primaryName.c_str(), alternativeName.c_str());

    for (const auto &record : ret) {

        auto contact = contactDB->contacts.getById(record.contactID);
        if (!contact.isValid()) {
            return records;
        }

        auto nrs = getNumbers(contact.numbersID);
        if (nrs.size() == 0) {
            LOG_DEBUG("Contact record does not contain any numbers.");
        }

        auto ring = contactDB->ringtones.getById(contact.ringID);
        if (!ring.isValid()) {
            return records;
        }

        auto address = contactDB->address.getById(contact.addressID);
        if (!address.isValid()) {
            return records;
        }

        records->push_back(ContactRecord{{.ID = record.ID},
                                         .primaryName     = record.namePrimary,
                                         .alternativeName = record.nameAlternative,
                                         .contactType     = contact.type,
                                         .numbers         = nrs,
                                         .address         = address.address,
                                         .note            = address.note,
                                         .mail            = address.mail,
                                         .assetPath       = ring.assetPath,
                                         .speeddial       = contact.speedDial,
                                         .groups          = contactDB->groups.getGroupsForContact(record.ID)});
    }

    return records;
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::Search(const char *primaryName,
                                                                           const char *alternativeName,
                                                                           const char *number)
{
    auto records = std::make_unique<std::vector<ContactRecord>>();

    auto ret = contactDB->contacts.Search(primaryName, alternativeName, number);

    for (const auto &record : ret) {
        auto contact = contactDB->contacts.getById(record.ID);
        if (!contact.isValid()) {
            return records;
        }

        auto nrs = getNumbers(contact.numbersID);
        if (nrs.size() == 0) {
            LOG_DEBUG("Contact record does not contain any numbers.");
        }

        auto ring = contactDB->ringtones.getById(contact.ringID);
        if (!ring.isValid()) {
            return records;
        }

        auto address = contactDB->address.getById(contact.addressID);
        if (!address.isValid()) {
            return records;
        }

        records->push_back(ContactRecord{{.ID = record.ID},
                                         .primaryName     = record.namePrimary,
                                         .alternativeName = record.nameAlternative,
                                         .contactType     = contact.type,
                                         .numbers         = nrs,
                                         .address         = address.address,
                                         .note            = address.note,
                                         .mail            = address.mail,
                                         .assetPath       = ring.assetPath,
                                         .speeddial       = contact.speedDial,
                                         .groups          = contactDB->groups.getGroupsForContact(record.ID)});
    }

    return records;
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetContactByNumber(const UTF8 &number)
{
    return GetLimitOffsetByField(0, 1, ContactRecordField::NumberUser, number.c_str());
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetByNumber(const UTF8 &number,
                                                                                CreateTempContact createTempContact)
{
    return GetByNumber(utils::PhoneNumber(number.c_str(), utils::country::Id::UNKNOWN).getView(), createTempContact);
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetByNumber(
    const utils::PhoneNumber::View &numberView, CreateTempContact createTempContact)
{
    auto number = numberView.getEntered();
    auto ret    = GetContactByNumber(number);
    if (ret->size() > 0) {
        return ret;
    }

    // Contact not found, create temporary one
    if (createTempContact == CreateTempContact::True) {
        LOG_INFO("Cannot find contact for number %s, creating temporary one", number.c_str());
        if (!Add(ContactRecord{
                {.ID = DB_ID_NONE},
                .contactType = ContactType::TEMPORARY,
                .numbers     = std::vector<ContactRecord::Number>{ContactRecord::Number(numberView)},
            })) {
            LOG_ERROR("Cannot add contact record");
            return ret;
        }

        ret->push_back(GetByID(contactDB->getLastInsertRowId()));
    }

    return ret;
}

utils::NumberHolderMatcher<std::vector, ContactNumberHolder> ContactRecordInterface::buildNumberMatcher(
    std::vector<ContactNumberHolder> &contactNumberHolders)
{
    auto numbers = getAllNumbers();

    for (const auto &number : numbers) {
        try {
            contactNumberHolders.push_back(ContactNumberHolder(number));
        }
        catch (const utils::PhoneNumber::Error &e) {
            LOG_WARN(
                "Skipping invalid phone number pair: (%s, %s)", number.numberUser.c_str(), number.numbere164.c_str());
            continue;
        }
    }

    return utils::NumberHolderMatcher<std::vector, ContactNumberHolder>(std::cbegin(contactNumberHolders),
                                                                        std::cend(contactNumberHolders));
}

std::optional<ContactRecord> ContactRecordInterface::MatchByNumber(const utils::PhoneNumber::View &numberView,
                                                                   CreateTempContact createTempContact,
                                                                   utils::PhoneNumber::Match matchLevel)
{
    std::vector<ContactNumberHolder> contactNumberHolders;
    auto numberMatcher = buildNumberMatcher(contactNumberHolders);

    auto matchedNumber = numberMatcher.bestMatch(utils::PhoneNumber(numberView), matchLevel);

    if (matchedNumber == numberMatcher.END) {
        if (createTempContact != CreateTempContact::True) {
            return std::nullopt;
        }

        LOG_INFO("Cannot find contact for number %s, creating temporary one", numberView.getEntered().c_str());
        if (!Add(ContactRecord{
                {.ID = DB_ID_NONE},
                .contactType = ContactType::TEMPORARY,
                .numbers     = std::vector<ContactRecord::Number>{ContactRecord::Number(numberView)},
            })) {
            LOG_FATAL("Cannot add contact record");
            return std::nullopt;
        }

        return GetByID(contactDB->getLastInsertRowId());
    }

    return GetByID(matchedNumber->getContactID());
}

std::unique_ptr<std::vector<ContactRecord>> ContactRecordInterface::GetBySpeedDial(UTF8 speedDial)
{
    return GetLimitOffsetByField(0, 1, ContactRecordField::SpeedDial, speedDial.c_str());
}

std::vector<ContactRecord::Number> ContactRecordInterface::getNumbers(const std::string &numbers_id)
{
    std::vector<ContactRecord::Number> nrs;
    for (auto nr_str : utils::split(numbers_id, ' ')) {
        auto nr = contactDB->number.getById(std::stol(nr_str));
        if (!nr.isValid()) {
            return nrs;
        }
        try {
            auto &&number = nr.numbere164.empty() ? utils::PhoneNumber(nr.numberUser, utils::country::Id::UNKNOWN)
                                                  : utils::PhoneNumber(nr.numberUser, nr.numbere164);
            nrs.push_back(ContactRecord::Number(number.getView(), nr.type));
        }
        catch (const utils::PhoneNumber::Error &e) {
            LOG_ERROR("Invalid contact's number pair: \"%s\" (\"%s\", \"%s\"). Using user number instead of a pair.",
                      e.what(),
                      nr.numberUser.c_str(),
                      nr.numbere164.c_str());
            nrs.push_back(ContactRecord::Number(
                utils::PhoneNumber(nr.numberUser, utils::country::Id::UNKNOWN).getView(), nr.type));
        }
    }
    return nrs;
}

ContactRecord::Number::Number()
{}

ContactRecord::Number::Number(const std::string &entered, const std::string &e164, ContactNumberType n_type)
    : number(utils::PhoneNumber(entered, e164).getView()), numberType(n_type)
{}

ContactRecord::Number::Number(const utils::PhoneNumber::View &number, ContactNumberType n_type)
    : number(number), numberType(n_type)
{}

std::vector<ContactsNumberTableRow> ContactRecordInterface::getAllNumbers()
{
    static const std::size_t singleDumpSize = 64;
    std::vector<ContactsNumberTableRow> v;

    std::size_t offset       = 0;
    std::size_t numbersCount = contactDB->number.count();
    while (offset < numbersCount) {
        auto singleRead = contactDB->number.getLimitOffset(offset, singleDumpSize);
        v.insert(std::end(v), std::begin(singleRead), std::end(singleRead));
        offset += singleDumpSize;
    }

    return v;
}

ContactNumberHolder::ContactNumberHolder(const ContactsNumberTableRow &numberRow)
    : row(numberRow), number(row.numbere164.empty() ? utils::PhoneNumber(row.numberUser)
                                                    : utils::PhoneNumber(row.numberUser, row.numbere164))
{}

const utils::PhoneNumber &ContactNumberHolder::getNumber() const
{
    return number;
}

std::uint32_t ContactNumberHolder::getContactID() const
{
    return row.contactID;
}

std::uint32_t ContactNumberHolder::getNumberID() const
{
    return row.ID;
}

void ContactRecord::addToFavourites(bool add)
{
    if (add) {
        groups.insert(ContactsDB::favouritesGroupId());
    }
    else {
        groups.erase(ContactsDB::favouritesGroupId());
    }
}

void ContactRecord::addToIce(bool add)
{
    if (add) {
        groups.insert(ContactsDB::iceGroupId());
    }
    else {
        groups.erase(ContactsDB::iceGroupId());
    }
}

void ContactRecord::addToBlocked(bool add)
{
    if (add) {
        groups.insert(ContactsDB::blockedGroupId());
        speeddial.clear();
    }
    else {
        groups.erase(ContactsDB::blockedGroupId());
    }
}

void ContactRecord::addToGroup(uint32_t groupId)
{
    groups.insert(groupId);
}

void ContactRecord::removeFromGroup(uint32_t groupId)
{
    groups.erase(groupId);
}

bool ContactRecord::isOnFavourites()
{
    return isOnGroup(ContactsDB::favouritesGroupId());
}

bool ContactRecord::isOnIce()
{
    return isOnGroup(ContactsDB::iceGroupId());
}

bool ContactRecord::isOnBlocked()
{
    return isOnGroup(ContactsDB::blockedGroupId());
}

bool ContactRecord::isOnGroup(uint32_t groupId)
{
    return groups.find(groupId) != groups.end();
}